Wednesday, November 15, 2023

Class Templates and Inheritance

It is possible to inherit from a template class. All the usual rules for inheritance and polymorphism apply. 

If new, derived class to be generic it should also be a template class; and pass its template parameter along to the base class.

Example:

template<class T>

class Base

{

private:

T data;

public:

void set(const T& val)

{

data= val;

}

};

template<class T>

class Derived: public Base<T>

{

public:

void set(const T& val);

};

template<class T>

void Derived<T> :: set(const T& v)

{

Base<T>::set(v);

}

 

The derived class may itself have template parameters. Please note there must be enough template parameters in the derived class to satisfy the requirements of the base class.

There is no requirement that your base class be a template. It is quite possible to have a template class inherit from a ‘normal’ class.

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top