Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ same name member in parent and child class

Tags:

c++

I met a problem in c++ programming if in c++ a parent and child class have a member with the same name:

#include <iostream>
using namespace std;

class A{
private:
    int x;
public:
    A(){x=1;}
    void SetX(int i)
    {
        x=i;
    }

};

class B:public A{
private:
    int x;
public:
    B(){}
   int GetX()
    {
        return x;
    }
};
int main() {
    B b;
    cout<<b.GetX()<<endl;
    b.SetX(10);
    cout<<b.GetX()<<endl;
    return 0;
}

The program result is:

-858993460
-858993460

Why? Which x is returned?
Thanks for your help.

like image 514
501 Avatar asked Jul 05 '18 05:07

501


2 Answers

In C++, a symbol in a child class is defined to "hide" any symbols with the same name in parent classes. This is so that it is not ambiguous which symbol the code is referring to. Note this isn't advisable, for precisely the confusion that your code shows!

There is the keyword using, which can "promote" certain parent class symbols into the child classes. But again, this is not advisable in this case!

Look at Overloading method in base class, with member variable as default for an example of where using is warranted, however.

like image 32
John Burger Avatar answered Sep 21 '22 14:09

John Burger


B::GetX will always return B::x.

A::SetX will always set A::x.

And since B::x is never initialized, its value will be indeterminate and printing it will lead to undefined behavior.

like image 57
Some programmer dude Avatar answered Sep 20 '22 14:09

Some programmer dude