Pure C ++ Virtual Methods

Consider this demo program:

#include <stdio.h>

class Base
{
public:
    virtual int f(int) =0;
    virtual int f(){ return f(0); }

    virtual ~Base(){ }
};

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }
};

int main(void)
{
    Derived obj;
    printf("%d\n", obj.f(1));  // This works, and returns 11
    printf("%d\n", obj.f());   // Adding this line gives me the error listed below
}

Which gives me the following compilation error:

virtualfunc.cpp: In functionint main()’:
virtualfunc.cpp:25:26: error: no matching function for call toDerived::f()virtualfunc.cpp:15:9: note: candidate is: virtual int Derived::f(int)

My hope was that the call obj.f()would lead to the call Base::obj.f(), since the derived class did not define it, which would lead to the call Derived::obj.f(0)to be defined in the Base class.

What am I doing wrong here? Is there any way to do this? In particular, I would like the call to obj.f()return 10.

(Also note that I understand that I can use the default argument to solve this problem, but this code is just a brief example of my problem, so please don't tell me to use the default arguments.)

Thank.

+5
3

, f (in Derived) hides f Base. , using. :

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }

//  vvvvvvvvvvvvvv
    using Base::f;
};
+3

, , , ++ .

obj.f();

++ f, , . obj Derived, Derived f. Derived::f(int), , ++ , , , , , . , , .

, ++, Base::f(), . Derived :

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }

    using Base::f;
};

using Base::f ++, Base f, Derived. , f, Derived::f(int), Base::f(). , , Base::f() .

, !

+8

f(int) Base::f, . , , , using Base::f; :

class Derived : public Base
{
public:

    using Base::f;   //note this line!

    int f(int i)
    {
        return (10 + i);
    }
};
+3

All Articles