daisy
daisy

Reputation: 23501

C++ template and inheritance, function not replaced in derived class

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;
}

Upvotes: 3

Views: 195

Answers (3)

juanchopanza
juanchopanza

Reputation: 227390

You should make cmp a virtual function in the base class:

virtual bool cmp (T & a, T & b);

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

Your cmp function must be declared virtual in A.

protected:
    virtual bool cmp (T & a, T & b)
    {
        return a > b;
    }

It will implicitly remain virtual in derived classes, although I'd explicitly declare cmp virtual in B as well, for clarity's sake.

Upvotes: 2

Andrew
Andrew

Reputation: 24846

You must declare polymorphic functions virtual. Otherwise you will not get polymorphic behaviour

virtual bool cmp (T & a, T & b)

Upvotes: 3

Related Questions