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.
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.
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.
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