Loading....
Coupon Accepted Successfully!

 

Class Templates And Inheritance

The template class can also act as a base class. When inheritance is applied with the template class, it helps compose a hierarchical data structure known as a container class.
  1. Derive a template class and add a new member to it. The base class should be of template type.
  2. Derive a class from a non-template class. Add a new template-type member to the derived class.
  3. It is also possible to derive classes from the template base class and to omit the template features of the derived classes.
As said earlier, the template characteristics of the base class can be omitted by declaring the type while deriving the class. All the template-based variables are substituted with basic data types. The following declaration illustrates the derivation of a class using a template featured base class.
 

template <class TL, . . .>

class XYZ

{

// Template-type data members and member functions

}

template <class TL, . . .>

class ABC: public XYZ <TL,…>

{

// Template-type data members and member functions

}

 
17.15 Write a program to derive a class using template base class.
#include<iostream.h>
#include<constream.h>
template<class T>
class one
{
protected:
T x,y;
void display()
{
cout<<x;
}
};
template <class S>
class two : public one <S>
{
S z;
public:
two (S a, S b, S c)
{
x=a;
y=b;
z=c;
}
void show()
{
cout<<“\n x=”<<x <<“ y=”<< y<<“ z=”<<z;
}
};
void main()
{
clrscr();
two <int> i(2,3,4) ;
i.show();
two <float> f(1.1,2.2,3.3);
f.show();
}
OUTPUT
x=2 y=3 z=4
x=1.1 y=2.2 z=3.3
 
Explanation: In the above program, class one is a base class, and class two is a template-derived class. Consider the statement
template <class S>
class two: public one <S>
 
Using the above statement, derivation is carried out. The base class name is followed by the template class name S. The function show() is a member of the derived class two(). In function main(), i and f are objects of class two. The object i is used to pass integer elements, and f is used to pass float numbers.




Test Your Skills Now!
Take a Quiz now
Reviewer Name