#include <iostream>
template<typename T>
class A
{
public:
typedef T atype;
A() {std::cout << "constructor A\n";}
~A() {std::cout << "destructor A\n";}
T m() const { return 1; }
void print() const
{
std::cout << m() << std::endl;
}
};
template<typename T>
class B : public A<T>
{
public:
B(): A<T>::A() {std::cout << "constructor B\n";}
~B() {std::cout << "destructor B\n";}
T m() const { return 2; }
};
int main()
{
A<double> a;
B<double> b;
a.print();
b.print();
return 0;
}
The output that the above peace of code gives is
constructor A
constructor A
constructor B
1
1
destructor B
destructor A
destructor A
but I would like to see
constructor A
constructor A
constructor B
1
2
destructor B
destructor A
destructor A
Basically, I want the print method which is inherited in the B class to evoke m() method which is declared in B class and not the one from the A class. I guess I have to use virtual functions, but I don't know which methods should be made virtual.
That is precisely what I would like to avoid. The code I have posted is just a huge simplification of my real code. The print function is much, much longer in my real code and I have couple of classes that are derived from A. So even though, this is the simplest solution I would like to avoid it, because than I would have to duplicate the print() method in all my derived classes.