***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Saturday, July 24, 2021

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.

No comments:

Post a Comment