简体   繁体   中英

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

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

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

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.

你应该让cmp成为基类中的虚函数:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM