VS2008 C ++ doesn't seem to be able to inherit an overloaded const method

I was just surprised to find that the following doesn't compile in VS2008. The compiler complains that it cannot convert parameter 1 from const int to int & thus demonstrating that it is not looking for an available method in the Base class.

Is there a good reason for this, or is this a flaw not found in other compilers?

struct Base
{
    virtual void doIt(int& v){cout << "Base NonConst v=" << v << endl;}
    virtual void doIt(const int& v) const {cout << "Base Const v=" << v << endl;}
};

struct Child : public Base
{
    virtual void doIt(int& v){cout << "Child NonConst v=" << v << endl;}    
};

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 99;
    const int& c_i = i;

    Child sc;
    sc.doIt(i);
    sc.doIt(c_i);
}

      

This compiles and works as expected if I remove the only overridden method in the Child class, or if I access the child class using the Base pointer (or, of course, if I override both methods in the child class).

However, overriding one method rather than the other seems to hide the method of the overridden base class when accessed directly from the Child class or a pointer to the Child class.

What the hell? Did I miss something?

+1


source to share


1 answer


This error you are getting will happen in every compiler (including gcc, msvc 2013, etc.)

no matching function for call to ‘Child::doIt(const int&)’ sc.doIt(c_i);

This is problem. You are overriding a function doIt

and only provide one override when the parent class has two. It won't look for the parent class as you are overriding it.

You must specify both overrides:



struct Child : public Base
{
    virtual void doIt(int& v){cout << "Child NonConst v=" << v << endl;}    
    virtual void doIt(const int& v) const { Base::doIt(v);}
};

      

OR you can also do the statement using

as shown in the picture (C ++ 11):

struct Child : public Base
{
    virtual void doIt(int& v){cout << "Child NonConst v=" << v << endl;}  

    using Base::doIt;
};

      

+2


source







All Articles