c++ – Why is this method not inherited?

Question:

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 func method of the parent class not exist in the child class even though the inheritance is public, and yet func2 does?

Answer:

Because you are inadvertently invoking the c++ called Name Hiding , from section § 3.3.10 of the current standard for c++ : (free translation)

Name Hiding: A name will be hidden by an explicit declaration with the same name in a nested declarative region or derived classes.

Keep in mind that doing this is considered bad practice since it is not very intuitive and it is recommended to avoid it. And it is not an error – since it is well stipulated in the standard – but rather a characteristic of the language.

The correct solution would be to use different names for the methods.

But if you have no other choice or you just don't want to use different names there is another feature of the language to make it explicitly visible in the derived class.

It is achieved using using

class Hija
  : public Padre
{
  public:
    using Padre::func; // <-- puedes hacerla visible así.

    int func(int param)
    { return param; }
};

Here you can see the program running after correction.

Note: Keep in mind that this will happen even if Hija::func is declared as private ( see example ).

Scroll to Top