Reputation: 11
This is about C++ (not java) inheritance and ambiguities in variable names.
Suppose that I am in this situation:
class A{
public:
void fct(){do something with x;}
private:
int x;
};
class B: public A{
private:
int x;
};
If I define some instance of the derived class
B foo;
and then call
foo.fct();
will fct()
act on A::x
or B::x
?
I would like it to be acting on A::x
. I wonder whether declaring x as private in class A is enough to make it safe against non-wanted ambiguities which may arise when defining derived classes.
I understand that just using a different name for B::x
would be the best thing to do... but suppose that one is "distracted" and forgets that the private A::x
exists, how bad the consequences would be?
Thank you!
Upvotes: 1
Views: 153
Reputation: 62613
Since fct
is non-virtual, it will always deal with x
as a member of it's own class. It won't know anything about any other x
s in any other classess.
However, if fct
were to declared virtual
and overridden in the child class, child override it would be called instead - and this one could be programmed so that it would use other x
.
Upvotes: 3
Reputation: 62532
Calling fct
will act on A::x
. The fact that derived classes have member variables with the same name is irrelevant since the member is private and hidden from them.
If it were able to see B::x
then that would be a bit like having virtual data!
Upvotes: 1