Category Archives: Theory

C++. Theory. Question-answer. Examples of program code. Base course C++. Object-oriented programming in C++.

C++. Inheritance of template classes. Adding a new type in inherited classes


Inheritance of template classes. Adding a new type in inherited classes

Before studying this topic, it is recommended that you familiarize yourself with the following topic:


Contents


Search other websites:

1. General information about inheritance of class templates

A class template that uses some generic type T can be inherited by another class. In the most general case, such inheritance looks like this:

template <class T>
class BaseClass
{
  // ...
};

template <class T>
class DerivedClass : public BaseClass<T>
{
  // ...
};

where

  • BaseClass, DerivedClass are the base and inherited class templates, respectively, that operate on the generic type T.

But there are times when an additional (different) type needs to be introduced into a derived class. Such a type can be a type that is close to the type of the base class. This could be the case, for example, when the two types are classes from the same hierarchy.

In this case, the base and derived class template code might look like this:

template <class T>
class BaseClass
{
  // ...
};

template <class T1, class T2>
class DerivedClass : public BaseClass<T1>
{
  // ...
};

here

  • BaseClass – base class in the template class hierarchy using the generic type T;
  • DerivedClass – inherited class. This class uses two generic types T1, T2.

 

2. Example. Type extension A<TA>, B<TA, TB>, C<TA, TB, TC>

In the example, for the purpose of demonstration, the addition of new types is used for the classes A<TA>, B<TA, TB>, C<TA, TB, TC> that form the inheritance hierarchy.

#include <iostream>
using namespace std;

template <class TA>
class A
{
protected:
  TA value;

public:
  A(TA value) : value(value) { }

  void Show()
  {
    cout << "A::value = " << value << endl;
  }

  TA Get() const { return value; }
};

template <class TA, class TB>
class B : public A<TA>
{
private:
  TB value;

public:
  B(TA valueA, TB valueB) :
    A<TA>(valueA), value(valueB) { }

  void Show()
  {
    A<TA>::Show();
    cout << "B::value = " << value << endl;
  }

  TA GetA() const { return A<TA>::value; }
  TB GetB() const { return value; }
};

template <class TA, class TB, class TC>
class C : public B<TA, TB>
{
private:
  TC value;

public:
  // Constructor
  C(TA valueA, TB valueB, TC valueC) :
  B<TA, TB>(valueA, valueB), value(valueC) { }

  void Show()
  {
    B<TA, TB>::Show();
    cout << "C::value = " << value << endl;
  }

  TA GetA() const { return A<TA>::value; }
  TB GetB() const { return B<TA, TB>::value; }
  TC GetC() const { return value; }
};

int main()
{
  B<int, double> objB(10, 5.5);
  objB.Show();
  C<int, float, double> objC(20, 2.5f, 7.3);
  objC.Show();
}

 


Related topics