Related
What is the difference between private and protected members in C++ classes?
I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.
What's the difference and which should I use?
Private members are only accessible within the class defining them.
Protected members are accessible in the class that defines them and in classes that inherit from that class.
Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.
Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.
Public members of a class A are accessible for all and everyone.
Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.
Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.
So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?
By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.
Protected members can be accessed from derived classes. Private ones can't.
class Base {
private:
int MyPrivateInt;
protected:
int MyProtectedInt;
public:
int MyPublicInt;
};
class Derived : Base
{
public:
int foo1() { return MyPrivateInt;} // Won't compile!
int foo2() { return MyProtectedInt;} // OK
int foo3() { return MyPublicInt;} // OK
};
class Unrelated
{
private:
Base B;
public:
int foo1() { return B.MyPrivateInt;} // Won't compile!
int foo2() { return B.MyProtectedInt;} // Won't compile
int foo3() { return B.MyPublicInt;} // OK
};
In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.
The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.
It all depends on what you want to do, and what you want the derived classes to be able to see.
class A
{
private:
int _privInt = 0;
int privFunc(){return 0;}
virtual int privVirtFunc(){return 0;}
protected:
int _protInt = 0;
int protFunc(){return 0;}
public:
int _publInt = 0;
int publFunc()
{
return privVirtFunc();
}
};
class B : public A
{
private:
virtual int privVirtFunc(){return 1;}
public:
void func()
{
_privInt = 1; // wont work
_protInt = 1; // will work
_publInt = 1; // will work
privFunc(); // wont work
privVirtFunc(); // will work, simply calls the derived version.
protFunc(); // will work
publFunc(); // will return 1 since it's overridden in this class
}
}
Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.
Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.
Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.
Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.
Of course friend functions throw this out the window, but oh well.
private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.
You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.
private = accessible by the mothership (base class) only
(ie only my parent can go into my parent's bedroom)
protected = accessible by mothership (base class), and her daughters
(ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)
public = accessible by mothership (base class), daughter, and everyone else
(ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)
Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.
private is preferred for member data. Members in C++ classes are private by default.
public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.
private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.
protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.
MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.
Members such as SetWindowText are public because you often need to access these members.
Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.
Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private
In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.
Private : Accessible by class member functions & friend function or friend class.
For C++ class this is default access specifier.
Protected: Accessible by class member functions, friend function or friend class & derived classes.
You can keep class member variable or function (even typedefs or inner classes) as private or protected as per your requirement.
Most of the time you keep class member as a private and add get/set functions to encapsulate. This helps in maintenance of code.
Generally private function is used when you want to keep your public functions modular or to eliminate repeated code instead of writing whole code in to single function. This helps in maintenance of code.
Refer this link for more detail.
Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule.
Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.
Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .
A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:
A pointer to a directly or indirectly derived class
A reference to a directly or indirectly derived class
An object of a directly or indirectly derived class
The protected keyword specifies access to class members in the
member-list up to the next access specifier (public or private) or the
end of the class definition. Class members declared as protected can
be used only by the following:
Member functions of the class that originally declared these members.
Friends of the class that originally declared these members.
Classes derived with public or protected access from the class that originally declared these members.
Direct privately derived classes that also have private access to protected members.
When preceding the name of a base class, the protected keyword
specifies that the public and protected members of the base class are
protected members of its derived classes.
Protected members are not as private as private members, which are
accessible only to members of the class in which they are declared,
but they are not as public as public members, which are accessible in
any function.
Protected members that are also declared as static are accessible to
any friend or member function of a derived class. Protected members
that are not declared as static are accessible to friends and member
functions in a derived class only through a pointer to, reference to,
or object of the derived class.
protected (C++)
What is the difference between private and protected members in C++ classes?
Other answers have stated:
public - accessible by all.
protected - accessible by derived classes (and friends).
private - restricted.
What's the difference and which should I use?
The C++ core guidelines gives the advice that data should always be private. I think this is good advice as it makes for 'data spaghetti' when you have derived classes that can access protected data. It makes much more sense for functions to be protected, but it depends on the use case.
For functions you have a choice. For data, you should make it private and provide protected accessor functions if needed. This gives more control over the class data.
private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class.
It also applies the same to inheritance .
But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''
What is the difference between private and protected members in C++ classes?
I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.
What's the difference and which should I use?
Private members are only accessible within the class defining them.
Protected members are accessible in the class that defines them and in classes that inherit from that class.
Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.
Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.
Public members of a class A are accessible for all and everyone.
Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.
Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.
So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?
By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.
Protected members can be accessed from derived classes. Private ones can't.
class Base {
private:
int MyPrivateInt;
protected:
int MyProtectedInt;
public:
int MyPublicInt;
};
class Derived : Base
{
public:
int foo1() { return MyPrivateInt;} // Won't compile!
int foo2() { return MyProtectedInt;} // OK
int foo3() { return MyPublicInt;} // OK
};
class Unrelated
{
private:
Base B;
public:
int foo1() { return B.MyPrivateInt;} // Won't compile!
int foo2() { return B.MyProtectedInt;} // Won't compile
int foo3() { return B.MyPublicInt;} // OK
};
In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.
The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.
It all depends on what you want to do, and what you want the derived classes to be able to see.
class A
{
private:
int _privInt = 0;
int privFunc(){return 0;}
virtual int privVirtFunc(){return 0;}
protected:
int _protInt = 0;
int protFunc(){return 0;}
public:
int _publInt = 0;
int publFunc()
{
return privVirtFunc();
}
};
class B : public A
{
private:
virtual int privVirtFunc(){return 1;}
public:
void func()
{
_privInt = 1; // wont work
_protInt = 1; // will work
_publInt = 1; // will work
privFunc(); // wont work
privVirtFunc(); // will work, simply calls the derived version.
protFunc(); // will work
publFunc(); // will return 1 since it's overridden in this class
}
}
Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.
Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.
Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.
Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.
Of course friend functions throw this out the window, but oh well.
private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.
You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.
private = accessible by the mothership (base class) only
(ie only my parent can go into my parent's bedroom)
protected = accessible by mothership (base class), and her daughters
(ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)
public = accessible by mothership (base class), daughter, and everyone else
(ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)
Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.
private is preferred for member data. Members in C++ classes are private by default.
public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.
private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.
protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.
MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.
Members such as SetWindowText are public because you often need to access these members.
Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.
Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private
In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.
Private : Accessible by class member functions & friend function or friend class.
For C++ class this is default access specifier.
Protected: Accessible by class member functions, friend function or friend class & derived classes.
You can keep class member variable or function (even typedefs or inner classes) as private or protected as per your requirement.
Most of the time you keep class member as a private and add get/set functions to encapsulate. This helps in maintenance of code.
Generally private function is used when you want to keep your public functions modular or to eliminate repeated code instead of writing whole code in to single function. This helps in maintenance of code.
Refer this link for more detail.
Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule.
Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.
Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .
A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:
A pointer to a directly or indirectly derived class
A reference to a directly or indirectly derived class
An object of a directly or indirectly derived class
The protected keyword specifies access to class members in the
member-list up to the next access specifier (public or private) or the
end of the class definition. Class members declared as protected can
be used only by the following:
Member functions of the class that originally declared these members.
Friends of the class that originally declared these members.
Classes derived with public or protected access from the class that originally declared these members.
Direct privately derived classes that also have private access to protected members.
When preceding the name of a base class, the protected keyword
specifies that the public and protected members of the base class are
protected members of its derived classes.
Protected members are not as private as private members, which are
accessible only to members of the class in which they are declared,
but they are not as public as public members, which are accessible in
any function.
Protected members that are also declared as static are accessible to
any friend or member function of a derived class. Protected members
that are not declared as static are accessible to friends and member
functions in a derived class only through a pointer to, reference to,
or object of the derived class.
protected (C++)
What is the difference between private and protected members in C++ classes?
Other answers have stated:
public - accessible by all.
protected - accessible by derived classes (and friends).
private - restricted.
What's the difference and which should I use?
The C++ core guidelines gives the advice that data should always be private. I think this is good advice as it makes for 'data spaghetti' when you have derived classes that can access protected data. It makes much more sense for functions to be protected, but it depends on the use case.
For functions you have a choice. For data, you should make it private and provide protected accessor functions if needed. This gives more control over the class data.
private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class.
It also applies the same to inheritance .
But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''
Please excuse my English skills; as I'm not a native speaker.
i got this code from my college textbook and im having trouble understanding it for hours...
#include<iostream>
using namespace std;
class base{
int a;
protected:
void seta(int a){this->a=a;}
public:
void showa(){cout<<a;}
};
class derived: private base{
int b;
protected:
void setb(int b){this->b=b;}
public:
void showb(){
seta(5); //1
showa(); //2
cout<<b;
}
};
class grandderived: private derived{
int c;
protected:
void setab(int x){
seta(x); //3
showa(); //4
setb(x); //5
}
};
int main(){
return 0;
}
here are my understandings so far:
class derived inherits class base as private, so everything inside class base are private. afaik private members cannot be accessed from subclasses.
so, number 1, 2 wont work.
class grandderived also inherits class derived as private, therefore 3,4, and 5 will also not work for the same reason.
but the answer tells me only number 3 and 4 wont work, and others will work.
i compiled it and yes it tells me the same.
am i misunderstanding something about how the inheritance works, or are there other things that i dont know of?
I believe this is what's happening:
The base class declared seta and showa as protected and public. This means they are accessible to subclasses.
derived inherits from base. This means it has access to everything protected and public from base, which includes seta and showa. The fact that it privately inherits base means that inherited members will be marked as private, and thus cannot be accessed in classes subclassing derived (i.e. grandderived).
This same pattern occurs between derived and grandderived.
Therefore: derived can access the methods from base, and grandderived can access the methods from derived, but NOT base.
You're close.
grandderived inherits from derived and marks it as private. However, this means that the methods that has inherited from derived will not be accessible from classes inheriting from grandderived. In the same way, derived inherits from base, marking it as private.
The effect is that grandderived can access the methods of derived but not base.
derived class inherits base class privately, which means all public and protected members of the base class becomes private in the derived class.
Even though it is a private inheritance, private can access to all protected and public members of base. So number 1 and 2 work.
base::seta is a protected member in base, it becomes private in derived's scope. grandderived can't access derived's private members, therefore number 3 and 4 won't work.
derived::setb, number 5, works as it is declared protected in class derived. Although it becomes private in the scope of grandderived, it is accessible from itself. It can't be inherited further.
Just as you can access your private members but others cannot, you can access your private base classes but others cannot. This is why class derived can access base::seta but class gradderived can't.
The main effect private inheritance has is that objects of the derived type can't be cast (from outside the class) to the base class type.
I used to see everywhere that private members of base class are never inherited in derived class, no matter how you inherit the base class (private or protected or public).
But below question has really confused me up. I don't know why the output of this program is 80. It should be 1 byte (which is the size of an empty class in C++) because private members are never inherited.
#include<iostream>
using namespace std;
class base
{
int arr[10];
};
class b1: public base { };
class b2: public base { };
class derived: public b1, public b2 {};
int main(void)
{
cout << sizeof(derived);
return 0;
}
This is mostly a problem of semantics and what different people refer to with inherited. When a type D inherits from a type B, each D object contains a full B object. From that point of view all of the members are there (and some people call this inherited). On the other hand, those members are not accessible from the members of D, and from that point of view the members are as if they were not there (and some people call this not inherited).
Private members of a base (no matter what accesibility) are not accessible from the derived types (assuming no friendship relationship), but they are there, an object of the derived type contains an object of the base type.
Yes, derived classes inherit members from all of their base classes.
The keywords private, public and protected affect only the accessibility of the items they are applied to. If something is not accessible in a particular context and you try to use it, the compiler will give you an error.
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 get inherited into the appropriate section of the sub-class (defined by class subclass : private base, which will take all public and protected members of base and put them into public, changing the word private to public puts them all in public and changing it to protected puts them all into protected).
So, when you create a sub-class you never receive anything from the private section of the previous class (the base class in this case), if this is true then an object of the sub-class should never have it's own version of a private variable or function from the base class correct?
Let's run over an example:
#include <iostream>
class myClass // Creates a class titled myClass with a public section and a private section.
{
public:
void setMyVariable();
int getMyVariable();
private:
int myVariable; // This private member variable should never be inherited.
};
class yourClass : public myClass {}; // Creates a sub-class of myClass that inherits all the public/protected members into the
// public section of yourClass. This should only inherit setMyVariable()
// and getMyVariable() since myVariable is private. This class does not over-ride any
// functions so it should be using the myClass version upon each call using a yourClass
// object. Correct?
int main()
{
myClass myObject; // Creates a myClass object called myObject.
yourClass yourObject; // Creates a yourClass object called yourObject
yourObject.setMyVariable(); // Calls setMyVariable() through yourObject. This in turn calls the myClass version of it because
// there is no function definition for a yourClass version of this function. This means that this
// can indeed access myVariable, but only the myClass version of it (there isn't a yourClass
// version because myVariable is never inherited).
std::cout << yourObject.getMyVariable() << std::endl; // Uses the yourClass version of getMyVariable() which in turn
// calls the myClass version, thus it returns the myClass myVariable
// value. yourClass never has a version of myVariable Correct?
std::cout << myObject.getMyVariable() << std::endl; // Calls the myClass version of getMyVariable() and prints myVariable.
return 0;
}
void myClass::setMyVariable()
{
myVariable = 15; // Sets myVariable in myClass to 15.
}
int myClass::getMyVariable()
{
return myVariable; // Returns myVariable from myClass.
}
Now, in theory based on what I think, this should print:
15
15
Due to it simply always using the myClass version of the functions (thus using the myClass myVariable). But, strangely, this is not the case. The result of running this program prints:
15
0
This makes me wonder, are we actually not only inheriting myVariable, but do we also have the ability to mess around with it? Clearly this is creating an alternate version of myVariable somehow otherwise there wouldn't be a 0 for the myClass version. We are indeed editing a second copy of myVariable by doing all this.
Can someone please explain this all to me, this has torn apart my understanding of inheritance.
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 get inherited into the appropriate section of the sub-class (defined by class subclass : private base, which will take all public and private members of base and put them into public, changing the word private to public puts them all in public and changing it to protected puts them all into protected).
There's a bit of confusion in this statement.
Recall that inheritance is defined for classes and structs in C++. Individual objects (ie. instances) do not inherit from other objects. Constructing an object using other objects is called composition.
When a class inherits from another class, it gets everything from that class, but the access level of the inherited fields may inhibit their use within the inheritor.
Furthermore, there are 3 kinds of inheritance for classes: private (which is the default), protected, and public. Each of them changes the access level of a class properties and methods when inherited by a subclass.
If we order the access levels in this manner: public, protected, private, from the least protected to the most protected, then we can define the inheritance modifiers as raising the access levels of the inherited class fields to at least the level they designate, in the derived class (ie. the class inheriting).
For instance, if class B inherits from class A with the protected inheritance modifier:
class B : protected A { /* ... */ };
then all the fields from A will have at least the protected level in B:
public fields become protected (public level is raised to protected),
protected fields stay protected (same access level, so no modification here),
private fields stay private (the access level is already above the modifier)
"When you create a sub-class you never receive anything from the private section of the [base class]. If this is true then an object of the sub-class should never have it's own version of a private variable or function from the base class, correct?"
No. The derived class inherits all the members of the base class, including the private ones. An object of the inherited class has those private members, but does not have direct access to them. It has access to public members of the base class that may have access to those members, but it (the derived class) may not have new member functions with such access:
class yourClass : public myClass
{
public:
void playByTheRules()
{
setMyVariable(); // perfectly legal, since setMyVariable() is public
}
void tamperWithMyVariable()
{
myVariable = 20; // this is illegal and will cause a compile-time error
}
};
myObject and yourObject are two different objects! Why should they share anything?
Think about it that way: Forget about inheritance and suppose you have a class Person with private int age; and public void setAge (int age) {...}. You then instantiate two objects:
Person bob;
Person bill;
bob.setAge(35);
Would you expect Bill to be 35 now, too? You wouldn't, right? Similarly, your myObject doesn't share its data with yourObject.
In response to your comment:
The class yourClass inherits from myClass. That means that both yourObject and myObject have their own myVariable, the latter obviously by definition, the former inherited from myClass.
Physically, every single member( including member functions) of base class goes into the subclass. Doesn't matter if they are private. Doesn't matter if you inherit them publically/protected-ly/privately. So in your example, yourClass contains all three of getMyVariable(), setMyVariable() and myVariable. All this is pretty simple, okay?
What matters is how we can access them. It is like when a file is deleted on your system. So, you should first understand the difference between a member being not there and a member being there but inaccessible. Assume for now that all inheritance takes place publically. Then, all public members of base class are public in derived class, protected members are protected and private members are inaccessible. They are inaccessible and not non-existent because there can be some member functions in protected and public sections in base class which access the private members of base class. Thus, we need all those private members of base which are accessed by public and protected member functions of base, for their functionality. Since there is no way that we can determine which member is needed by which member function in a simple manner, we include all private members of the base class in derived class. All this simply means that in a derived class, a private member can be modified by only through the base class' member functions.
Note: every private member has to be accessed, directly or indirectly [through another private member function which in turn is called by a public/protected member function] by a public/protected meber function, else it has no use.
So, we know till now that a private member variable of base class has its use in derived class i.e. for the functionality of its public/protected member functions. But they can't be accessed directly in base class.
Now, we turn our attention to private/public inheritance. For public inheritance, it means that all the accessible members of base class (that is, the public and protected members) can not be at a level more permissive than public. Since, public is the most permissive level, public and protected members remain public. But at protected and private inheritance, both become protected and private in the derived class, respectively. Inthe latter case, since all these members are private, they can't be accessed further in the hierarchy chain, but can be accessed by the given derived class all the same.
Thus, the level of each base class member in derived class is the lesser of their level in derived class () and the type of inheritance (public/protected/private).
Same concept applies to the functions outside the class. For them private and protected members are inaccessible but they do exist and can be accessed by the public member functions.
And taking your case as a final example, setMyvariable() and getMyVariable() can access myVariable in the derived class. But no function specified in derived class can access myVariable. Modifying your class:
class myClass
{
public:
void setMyVariable();
int getMyVariable();
private:
int myVariable;
};
class yourClass : public myClass
{
public:
// void yourFunction() { myVariable = 1; }
/*Removing comment creates error; derived class functions can't access myVariable*/
};
Further: you can add exceptions to the type of inheritance too e.g. a private inheritance except a member made public in derived class. But that is another question altogether.
You never call myObject.setMyVariable(), so myObject.getMyVariable() will not return 15.
private does not imply static.
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:
The name myClass::myVariable is private.
The name 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.
This may help
#include<iostream>
using namespace std;
class A
{
int b;
};
class B : private A
{
};
int main()
{
C obj;
cout<<sizeof(obj);
return 0;
}