stu nicholls dot com | menu - Professional dropdown #3

click here

Templates

Example of class which creates an integer array

Class vector{
     int *v;
     int size;
Public:
   vector(int m) { v= new int[size=m];
        for (int i=0; i< size; i++) v[i]=0;
       ……}
Now if we want to create a float array again the class needed to be re-written. But if we use templates to create an array, the same template can be made use of to create different types of arrays

Syntax:

template <class T>
   class classname
     {
      //
     Different statements
    };
Template 
   class vector
     {
     T *v; // type T vector
     int size;
     public:
      vector(int m)
        { v=new T[size=m];
       for(int i=0; i
  • Class template definition is similar to an ordinary class definition except that prefix template and the use of type T.
  • This prefix tells the compiler that we are going to declare a template and use T as a type name in the declaration.
  • Thus the vector has become the parameterized class with the type T as its parameter.
  • T may be substituted by any data type including the user defined types.
  • Now, we can create vectors for holding different data types.
Example: 
  vector  v1(10);  
    // 10 element int vector
  vector  v2(25); 
   // 25 element float vector

   Syntax:
Classname  objectname(arglist);
Footer1