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 function ‘int main()’:
virtualfunc.cpp:25:26: error: no matching function for call to ‘Derived::f()’
virtualfunc.cpp:15:9: note: candidate is: virtual int Derived::f(int)
My hope was that a call to obj.f()
would result in a call to Base::obj.f()
since the derived class doesn't define it, which would then result in a call to Derived::obj.f(0)
per the definition in class Base.
What am I doing wrong here? Is there a way to accomplish this? Specifically, I'd like the call to obj.f()
to return 10.
(Also please note that I realize I could use a default argument to solve this, but this code is simply a concise example of my issue, so please don't tell me to use default arguments.)
Thanks.
f
function inDerived
hides
the other functions, defined inBase
. That's why you get this error – Sangsangerusing Base::f;
in the Derived class definition fixed it. Thanks! – Escalera