class A{private:
int X;
protected:
void modify(int Y){X=X+Y;}
};
class B:public A{private: int X; };
class C:public B{private: int X; };
How to modify X fields of B,C classes with the modify function within this class tree declaration?
Please note this is an extract. Actual one contains much more members.
You can't. A modifying one of its children's members assumes that it actually is an object of that child (ie: it defeats the entire point of having a parent class).
What you can do is make modify virtual, that way it can call B::modify:
1 2 3 4 5 6 7 8 9 10 11
class A
{
//...
virtualvoid modify(int Y) { X=X+Y; }
};
class B : public A
{
//...
virtualvoid modify(int Y) { X=X+Y; } // this modifies B::X, not A::X
};
Of course... this begs the question of why you need two different X's. Can't B and C just use A::X? Why do they need a separate X?
The thing about C++ class methods is if one intend to make it can be overridden by sub-class, one need to put a virtual keyword. However for Java, by default all parent classes methods can be overridden, no need extra keyword specifier. This make it easy for Java programmers.
I guess for C++, virtual impose certain performance hits and the default is it cannot be overridden. So if one toggle between C++ and Java, these are language differences one need to take note as it is very easy to forget when one switches over to and fro due to different project requirement needs using different languages.