You are on page 1of 32

Introduction to Programming

Lecture 42
template <class T>
Template
Classes
Stack
Last In
First Out
template <class T>
class ClassName
{
definition
}
Member function
template <class T>
Class_Name <T> :: Function_Name (Arguments)
{
// body of function
}
Class_Name :: Function_Name ( Arguments )
{
// body of function
}
Example
template <class T>
class Number
{
private :
T MyNumber ;
public:
Number ( T n ) ;
display ( ) ;
}
Example

Number <int> x ;
Number <double> y ;
Non Type
Parameters
template <class T , int elements>
int x [ 100 ] ;
Static
Member
Variables
Number <int> x ;
Example
class PhoneCall
{
private :
int lengthOfCall ;
char billCode ;
public :
PhoneCall ( const int i , char b ) ;
PhoneCall ( PoneCall & p ) ;
PhoneCall PhoneCall :: operator - ( void ) ;
void display ( void ) ;
};
Example
PhoneCall PhoneCall :: operator -( void )
{
PhoneCall temp ( * this ) ;
temp.billCode = 'C' ;
return ( temp ) ;
}
Friend
Function
‘a’ is a 2 is an
object of a integer value
class

a+2;
a+2;
should be same
as
2+a;
friend f ( ) ;
friend f ( x <T> & ) ;
friend f ( X <int> & ) ;
friend class Y ;
friend A :: f ( ) ;
friend A :: f ( X< T > & )
template <class T>
Example
class Stack
{
private :
int size ;
T array [ ] ;
public :
Stack ( ) ;
void push ( T ) ;
T pop ( ) ;
bool isEmpty ( ) ;
bool isFull ( ) ;
// Etc.
};
Example

Stack <int> x ;
Stack <double> x ;
Last In
First Out
Queue
Link List
First In
First Out
STL
Standard
Template Library

You might also like