Basically from C++ FAQ I learned that:
A virtual function allows derived classes to replace the
implementation provided by the base class. The compiler makes sure the
replacement is always called whenever the object in question is
actually of the derived class, even if the object is accessed by a
base pointer rather than a derived pointer. This allows algorithms in
the base class to be replaced in the derived class, even if users
don’t know about the derived class.
Though, using templates this becomes no more correct.
I need to have a template class which is derived by another template class. After that I found it makes no sense to have a virtual function in a base template class, googling around I found that there is a technique to overcome limitations of polymorphism in generic programming called Type Erasure.
Examples and tutorials I’ve read, are almost irrelevant to my needs. Also I’m not sure if I understood concepts of Type Erasure correctly. Being a beginner, I need to simply do:
template <typename T>
class Foo
{
public:
virtual void doX(){cout<<"doX from Foo"<<endl;}
};
template <typename T>
class Bar : public Foo<T>
{
public:
void doX(){cout<<"doX from Bar"<<endl;}
};
And,
Foo<int>* p;
Foo<int> i;
i.doX(); // "doX from Foo", it's ok
Bar<int> j;
j.doX(); // "doX from Bar", it's ok
p=&i;
p->doX(); // should be "doX from Foo", it's ok
p=&j;
p->doX(); // I expect "doX from Bar", but it's "doX from Foo"
EDIT:
My question is how to implement above behavior? Without templates, It works as expected. I need same for general classes.
Simply, I have a base class B. It’s a template class. It has a virtual function. And also I have a subclass of B which is a template class too, and it should reimplement some behavior of B (somehow implement virtual function of B).
EDIT2 : Just edited the title.
I was compiling my code with g++ 4.6.3 compiler using flag -std=c++0x because I need std::thread and std::unique_ptr in my code. Surprisingly, removing the -std=c++0x the above code works as expected. I also tried g++ 4.7 and there was no problem with both 2011 and 2003 standards.
Because function doX is not virtual. In derived class you hide function doX, not overload, so dynamic polymorphysm not work.
EDIT.
GCC 4.6.3 have bug in such case, when you use -std=c++0x flag.
EDIT2.
Possibly GCC 4.6.3 have no such bug and problem is with TS compiler.