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;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are access specifiers? Should I inherit with private, protected or public?
How can I create a derived class in C++ which preserves the properties and methods' access specifier like this:
class Base
{
private:
void base_private();
protected:
void base_protected();
public:
void base_public();
};
class A: [what type is appropriate here?] Base
{
public:
void test() {
base_protected(); // Ok
}
};
class B: [what type is appropriate here?] A
{
public:
void test() {
base_protected(); // Ok
}
};
int main()
{
A a;
B b;
a.base_public(); // Ok
a.base_protected(); // Not Ok
b.base_protected(); // Not Ok
b.test(); // Ok
return 0;
}
I mean base_protected() method is still protected in derived classes but base_public() is public.
Lets consider the availability of members of Base:
base_private is not available to clients but available to Base itself
base_protected is not available to clients but available to Base itself
base_public is available to both clients and Base
Now, if you have class A : public Base (public inheritance), the availability of the members of Base will be:
base_private is not available to clients and not available to A itself
base_protected is not available to clients but available to A itself
base_public is available to both clients and A
Now, what you're asking about is how to keep the same client interface for both classes, Base and A. If you look at the availability of the members for clients in the lists above, you will see that it is precisely the same for Base and A: base_private is not available; base_protected is not available; and base_public is available.
The only thing that has changed between Base and A is that A cannot access the members that are private to Base. That's the whole point of the protected access control - it gives derived classes access to their base classes members without making them available to clients.
So public inheritance is what you need.
A derived class can access public and protected members of a base class, no matter whether you inherit private, protected or public.
When you inherit private all members of the base class are considered private for derived classes of A. Similar for protected inheritance, derived classes of A may access protected and public members of Base.
In both cases, private and protected inheritance, the members of Base are not accessible to the "public".
And now to answer your question, use public inheritance to preserve the access specifiers of the base class.
As far as I understand the reason that we cannot pass a derived class object to a base class reference for private inheritance is that Since Derived is privately inherited from Base, the default constructor of Base would be called before the constructor of Derived. But because it is private and not inherited to Derived, we get a compiler error.
But, if I try to create a public constructor for Base and inherit from Derived privately and then re-assign the public status to Base's constructor will it allow me to pass a derived's instance to Base reference?
I tried it as follows,
#include <iostream>
using namespace std;
class base
{
public:
base(){}
void print(){ puts("In base"); }
};
class derived : private base
{
public:
base::base; /* Throws an error - Declaration doesnt declare anything*/
void print(){ puts("In derived"); }
};
void func(base& bRef)
{
}
int main()
{
derived dObj;
func(dObj); /* Throws an error - 'base' is an inaccessible base of derived */
}
It throws an error for base::base (publicizing privately inherited constructor to public).
Is what I am trying valid? Can anyone please tell me?
The reason we cannot have a base class reference to a derived object that inherits privately is because that would violate the Liskov Substitution Principle: the derived object IS-NOT-A base class object because it does not provide the base class public interface. You cannot work around this
For this reason, private inheritance is a way of reusing implementation and not when you want to make a more specialized type. As this can most of the time be done with composition (i.e. having a member of the base class instead of privately deriving), private inheritance might be a bad code smell.
You can read here (be sure to follow all the links) for more information on when private inheritance is a good option (summary: when there simply is no other choice).
No, it is not valid to point to an object of Derived with a pointer or reference of Base class. If it were possible, then the whole purpose of private inheritance (hide the fact that the derived class inherits part (or the whole) of its functionality from the base class) would be useless.
Say you have a method foo() in the base class. You don't want this method to be called. But if it were possible to point the object from a pointer of the base class, then it would also be possible to call foo().
Base * ptrBase = &objDerived; // Let's suppose this would compile
ptrBase->foo(); // Now we can call foo() (?)
When you declare private inheritance, is as if the Derived class where not related to the base class. It is just you, the developer, the only one that should "know" that this relationship exist, and actually you should forget about it, because it just won't work.
Private inheritance is just there solely as a reusability mechanism, not as a true inheritance mechanism. It is not recommended to even use it, since you can obtain a better result by simply applying composition (i.e. just make an attribute of class Base in Derived).
I have a class A, which have a field val declared as private.
I want to declare a class B, that inherit from A and have an access to val.
Is there a way to do it on C++?
I want to do it because I need to overload some functions of A, without changing A code at all.
Thanks.
Quick answer: You don't. Thats what the protected key-word is for, which you want to use if you want to grant access to subclasses but no-one else.
private means that no-one has access to those variables, not even subclasses.
If you cannot change code in A at all, maybe there is a public/protected access method for that variable. Otherwise these variables are not meant to be accessed from subclasses and only hacks can help (which I don't encourage!).
Private members of a base class can only be accessed by base member functions (not derived classes). So you have no rights not even a chance to do so :)
class Base
public: can be accessed by anybody
private: can only be accessed by only base member functions (not
derived classes)
protected: can be accessed by both base member functions and derived
classes
Well, if you have access to base class, you can declare class B as friend class. But as others explained it: because you can, it does not mean it's good idea. Use protected members, if you want derived classes to be able to access them.
It is doable as describe in this Guru of the Week - GotW #76 - Uses and Abuses of Access Rights. But it's should be considered a last resort.
You need to define it as protected. Protected members are inherited to child classes but are not accessible from the outside world.
You can access the private members of a base class say A through an inherited member function of A
#include<iostream>
using namespace std;
class A{
int a;
public:
A(){};
A(int val){a=val;};
int get_a(){//To access a private variable it must be initialized here
a=10;
return a;
}
};
class B: public A{
int b;
public:
B(){};
B(int val){b=val;};
void get(){
cout<<get_a();
}
};
int main(){
A ob1(2);
cout<<ob1.get_a()<<endl;
B ob2(4);
ob2.get();
return 0;
}