Page 312 - DCAP404 _Object Oriented Programming
P. 312
Unit 14: Advanced Concept in C++
in which a and b are integer type variables. When the user invokes max ( ) , using two int values, Notes
the identifier, ‘type’, is substituted with int, wherever it is present. Now max ( ) works just like
the function int max (int, int) defined earlier, to compare two int values. Similarly, if max ( ) is
invoked using two double values, ’type’ is replaced with ‘double’. This process of substitution,
depending on the parameter type passed to the function, is called template instantiation. The
template specifies how individual functions will be constructed, given a set of actual types. The
template facility allows the creation of a blueprint for a function like max ( ).
Did u know? Is the template or blueprint can then be instantiated for all data types?
Yes, the template or blueprint can then be instantiated for all data types, eliminating
duplication of the source code. The identifier, ’type’, can be used within the function body
of a function that, otherwise, remains unchanged.
Example: The template for a function called square 9, which calculates the square of any
number (int, float, or double type) passed to it can be given as:
# include < iostream.h >
template < class type >
type square ( type a)
{
type b;
b= a*a ;
return b.;
}
int main ( )
{
cout << “ square (25 ) : “ << square ( 25) << endl;
cout << “ square 40 : “ << square 40 << endl;
return 0 ;
}
Output
Square ( 25 . 45F) : 1125
Square 90 : 1600
Here is another example of the use of template function. Consider the following classes:
class IRON
{
private :
float density ;
public :
IRON ( ) {density = 8.9 }
Float Density ( ) { return density ;}
} ;
LOVELY PROFESSIONAL UNIVERSITY 305