class Base {
public:
virtual void f();
void f(int);
virtual ~Base();
};
class Derived : public Base {
public:
void f();
};
int main()
{
Derived *ptr = new Derived;
ptr->f(1);
delete ptr;
return 0;
}
ptr->f(1); is showing the following error: "too many arguments in function call".
Why is this isn't possible? isn't derived inherited all the functions form base and is free to use any of them? I could call it explicitly and it would work but why isn't this allowed?
What you are seeing is called hiding.
When you override the function void f()
in the Derived
class, you hide all other variants of the f
function in the Base
class.
You can solve this with the using
keyword:
class Derived : public Base {
public:
using Base::f; // Pull all `f` symbols from the base class into the scope of this class
void f() override; // Override the non-argument version
};
As mentioned by @Some Programming Dude : it is because of Hiding.
To understand hiding in relatively simpler language
Inheritance
is meant to bring Base
class variables / functions in Derived
class.
But, on 1 condition : "If its not already available in Derived Class"
Since f()
is already available in Derived
, it doesn't make sense to look at Base
class from compiler perspective.
That's the precise reason why you need to scope clarify while calling this function
void main()
{
Derived *ptr = new Derived;
ptr->Base::f(1);
delete ptr;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With