Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't call base class's method when another overload present in derived class

Tags:

c++

I get a compiler error "function does not take 0 arguments" when compiling the following code.

class A
{
public:
    int Foo()
    {
        return 1;
    }

protected:
    virtual void Foo(int& n)
    {
        n += 1;
    }
};

class B : public A
{
protected:
    // Override of A
    void Foo(int& n)
    {
        n += 2;
    }
};


int main(int argc, char* argv[])
{

    B b;
    int n = b.Foo();
    return n;
}

It looks like the compiler insists on calling overload B::Foo(int&) instead of A::Foo(). I must be missing something obvious here. Any pointers to C++ standard that explain the compiler's behaviour will be appreciated.

I do realise that "int n = ((A)b).Foo();" will make the compiler happy but this is not an ideal solution for me.

Thanks.

like image 745
bdristan Avatar asked Sep 28 '22 03:09

bdristan


1 Answers

Add this line:

using A::Foo;

in class B (public part) and it will work.

In this case Foo from B hides Foo from A. One of the C++ strange behaviors.

like image 51
agnor Avatar answered Oct 06 '22 00:10

agnor