Basically as far as I know, when you create a base class with a public, protected, and private section and variables/functions in each the public and protected sections will
After:
class yourClass : public myClass {};
there is still only one member variable. But there are two ways of accessing it by name: myClass::myVariable
, and yourClass::myVariable
.
In these expressions, the class name is known as the naming class. The second key thing to understand is that access rights apply to the combination of naming class and member name; not just to the member name and not to the variable itself.
If a member is mentioned without explicitly having the naming class present, then the naming class is inferred from the type of the expression on the left of the .
or ->
that named the member (with this->
being implied if there is no such expression).
Furthermore, there are really four possible types of access: public
, protected
, private
, and no access. You can't declare a member as having no access, but that situation arises when a private member is inherited.
Applying all this theory to your example:
myClass::myVariable
is private
.yourClass::myVariable
is no access.To reiterate, there is only actually one variable, but it may be named in two different ways, and the access rights differ depending on which name is used.
Finally, back to your original example. myObject
and yourObject
are different objects. I think what you intended to write, or what you are mentally imagining is actually this situation:
yourClass yourObject;
myClass& myObject = yourObject;
// ^^^
which means myObject
names the base class part of yourObject
. Then after:
yourObject.setMyVariable();
the variable is set to 15
, and so
std::cout << myObject.getMyVariable() << std::endl;
would output 15
because there is indeed only one variable.