Search code examples
classtemplatesinheritanceradix

Inheritance with templates


#include<iostream>

using namespace std; 

class C
 {
public:
C (){};
virtual void nothing()=0;
virtual ~C (){};
 };

class A : public C
{
public:
 A (){};
 virtual void nothing(){};
};
class B:public A 
{
public:
 B(){};
 void nothing(){};
};

template <class T>
void hi(T){
cout << " i am something\n";
}

template <>
void hi<A>(A)
{
cout << " I am A\n";
}

template <>
void hi<B>(B)
{
cout << " I am B\n";
}

int main ( ) 
{
C *array [] = {new A,new B};
hi (*array [0]);
hi (*array [1]);

delete array [0];
delete array [1];
return 0; 

} 

Out: i am something I am something

Currently I am writing a program that has to deal with
Inherited types and specialised templates. In the example above I would l would like to see I am A I am B Is there a way to properly invoke the functions corresponding to the objects although I am handling a base class array? I am not sure if type checking and conversion via dynamic_cast is the most elegant solution. Note that this is just an excerpt from a larger program. Thank you in advance


Solution

  • In the main routine, the three lines shown below create an array of C*. So any element of that array is treated as a C* regardless of what the actual type of the element is. That is, when you pass *array [0] to the function hi(), the function that gets called is hi(C) which resolves to the generic hi function, not either of the specialized functions.

    C *array [] = {new A,new B};
    hi (*array [0]);
    hi (*array [1]);
    

    In order to make hi<A> be invoked, you either have to store the pointer to the new object in a variable of type A* or you need to cast the C* to an A*.

    In a case like this, a virtual function of C, overridden in A and B, may serve the purpose better.