Is it possible to change a derived class’ variable from the super in C++?
(Using an example may make my question more clear..)
Say I have the following classes and functions:
class SuperClass // super class
{
int myClassVariable;
public:
virtual void modify()
{
myClassVariable = 10;
}
};
class DerivedClass : public SuperClass // derived class
{
int myClassVariable;
public:
void modify()
{
super::modify();
}
};
And if I do the following:
DerivedClass d;
d.modify();
Question: Who’s myClassVariable gets modified to 10? The super class or the derived class?
(Thank you in advance for you patience and help.. hope my question isn’t a stupid one!)
Thanks 🙂
It’s the super class, since the member is modified in the super class and a member can’t be virtual, only methods can be virtual.
Also note that modify() isn’t virtual in the derived class (with respect to the super class), it’s only virtual to children of the derived class, since modify() wasn’t declared virtual in the super class.