0

Why doesn't this program give an error if there seems to be a naming conflict between the inherited foo() function from the Parent class and the exactly same header function foo() in the child class?

This is the code:

class Parent {
public:
    Parent() {}
protected:
    void foo() { std::cout << "foo-of-Parent" << std::endl;}
};


class Child:public Parent {
public:
    Child() {};
    void foo() { std::cout << "foo-of-Child" << std::endl; }
};

int main(){

Child john;
john.foo();   

return 0;
}

Is the inherited function a member with kind of less priority in Child?

M-J
  • 1,028
  • 11
  • 15
  • 4
    What you have there is *name hiding*. You may want to check some good C++ resources [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). It requires a bit of effort to properly explain here, so I advice you to check those resources – WhiZTiM Jun 02 '17 at 20:36
  • There is no inheritance in your example as foo isn't virtual. Thus foo in Child is called because john is of type Child. – germanfr Jun 02 '17 at 20:36
  • Because functions are defined in different scopes? – Algirdas Preidžius Jun 02 '17 at 20:36
  • 4
    @germanfr: You mean there's no polymorphism. There is inheritance. – Fred Larson Jun 02 '17 at 20:37
  • @WhiZTiM thanks I'll check that. – M-J Jun 02 '17 at 20:40
  • 1
    You could call the `foo` from `Parent` with `john.Parent::foo();` (as long as you make `foo` public in `Parent`). – DeiDei Jun 02 '17 at 20:40

1 Answers1

4

Why doesn't this program give an error if there seems to be a naming conflict

There is no error because there is no naming conflict. In C++, you may define identifiers of same name in different namespaces. The names of the child class hide (this is a technical term) the names of the parent class. This means that the hidden names of the parent class will not be found by unqualified lookup. They can still be found with qualified lookup. An example:

void Child::foo() {
    Parent::foo();
}
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • So if I'm not taking it right, we can say that "permission to access" the foo() of the Parent class is given to the Child class. Am I right? – M-J Jun 02 '17 at 20:46
  • 1
    @M-J that is what the `protected` access specifier does. It gives access only to self, and children. Code from outside of either class can only access `Child::foo` since it is public, but not `Parent::foo` since it is not. – eerorika Jun 02 '17 at 20:46