Here I attached a minimal case, where in child class, cmp will replace the one in parent class, but it doesn’t work, it always calls the one from the parent
#include <iostream>
template <typename T>
class A
{
public:
void tell(T a, T b)
{
std::cout << (cmp (a, b) ? a : b) << " is better" << std::endl;
}
protected:
bool cmp (T & a, T & b)
{
return a > b;
}
};
template <typename T>
class B: public A<T>
{
protected:
bool cmp (T & a, T & b)
{
return a < b;
}
};
int main ( int argc , char **argv )
{
B<int> b;
// should be: 3 is better here
b.tell(5, 3);
return 0;
}
Your
cmpfunction must be declaredvirtualinA.It will implicitly remain virtual in derived classes, although I’d explicitly declare
cmpvirtual inBas well, for clarity’s sake.