Given the following code:
class Padre
{
public:
int func()
{ return 0; }
int func2()
{ return 0; }
};
class Hija
: public Padre
{
public:
int func(int param)
{ return param; }
};
int main()
{
Hija clase;
std::cout << clase.func(); << std::endl; // ERROR
std::cout << clase.func(5); << std::endl; // OK
std::cout << clase.func2(); << std::endl; // OK
}
Why does the method func
of the parent class not exist in the child class despite the fact that the inheritance is public, and yet it func2
does?
Because you are inadvertently invoking the Name Hiding
c++
call feature , from section § 3.3.10 of the current standard for :c++
Note that doing this is considered bad practice as it is unintuitive and should be avoided. And it is not an error -since it is well stipulated in the standard- but rather a feature of the language.
The correct solution would be to use different names for the methods.
But if you have no other choice or just don't want to use different names there is another language feature to make it visible explicitly in the derived class.
It is achieved using
using
Here you can see the program running after the fix.
Note: Be aware that this will happen even if
Hija::func
declared asprivate
( see example ).