Home > Back-end >  Is it possible to inherit from a template base class with virtual function overriding with template
Is it possible to inherit from a template base class with virtual function overriding with template

Time:12-25

When I use class Derived: public Base<int*>, I thought the Base class template is a member function like virtual void foo(const int* a) {} because of explicit instantiation during compilation. However, If I write like this, it never shows "Derived class". What's happening?

#include <iostream>
using namespace std;

template<typename T>
class Base
{
public:
    virtual void foo(const T a)
    {
        cout << "Base foo" << endl;
    }
};

class Derived : public Base<int*> // But " template<typename T> class Derived : public Base<T> {...} " works fine...
{
public:
    virtual void foo(const int* a)
    {
        cout << "Derived foo" << endl;
    }
};

int main()
{
    Base<int*>* p = new Derived;
    p->foo(0);  // "Base foo"
}

CodePudding user response:

Note that for const T, const is qualified on T itself. Then given T is int*, the parameter type of Base<T>::foo, i.e. const T would be int * const (const pointer to non-const int), but not const int * (non-const pointer to const int).

You should change Derived::foo to

virtual void foo(int* const a)
{
    cout << "Derived foo" << endl;
}

Other issues: (1) don't forget to delete the pointer p at last; (2) Base should have a virtual destructor.

LIVE

  • Related