jeudi 5 mars 2015

Polymorphism and overriding a method from a class template in C++


I would like to have a class template with basic implementations of my methods, and a set of subclasses that use the template class with particular types (double, int, char*) and override some subset of those base implementations, as needed. However, my overridden methods don't seem to get called unless I declare the object as an instance of the subclass. In exploring this problem I came up with the following code:



#include <iostream>

template <typename T>
class BaseClass {
public:
virtual void print1 (T thing) {
std::cout << "Base print1: " << thing << std::endl;
}

virtual void print2 (T thing) {
std::cout << "Base print2: " << thing << std::endl;
}
};

class IntClass : public BaseClass<int> {
public:
void print2 (int thing) {
std::cout << "Int print2: " << thing << std::endl;
}
};

int main()
{
BaseClass<int> thing = IntClass();
thing.print1(1);
thing.print2(1);

IntClass thing2 = IntClass();
thing2.print1(2);
thing2.print2(2);

return 0;
}


My expected output would be:



Base print1: 1
Int print2: 1
Base print1: 2
Int print2: 2


But instead, I get:



Base print1: 1
Base print2: 1
Base print1: 2
Int print2: 2


Is it possible to achieve my goal here, or am I better off creating separate base classes for each type in this case? Apologies if my terminology is a bit off - I am relatively new to C++.




Aucun commentaire:

Enregistrer un commentaire