-
Everything is Inherited?
I tried this :-
Code:
#include<iostream>
using namespace std;
class A
{
int x;
};
class B:private A
{
int y;
public:
void foo()
{
cout<<x; // error
}
};
int main()
{
A a;
B b;
cout<<sizeof(a); // 4
cout<<sizeof(b); // 8
b.foo();
}
code suggests me, that even the private members of the base class are actually inherited and present in derived objects <sizeof>, but accessibility only restricts us to which members i can actually access from my derived object or infact in my derived class
I would appreciated any confirmation
-
That is true.
Think of it this way: If variables from the base class weren't also kept around in derived classes, all functions from the base class that used those variables would now have nothing to work with.
-
I'm not sure I understand what you're saying. 'x' is private in class A, so it can only be accessed by members of class A. If you declared it as protected (or public), then your code would compile.
-
I believe you misunderstand the purpose of access specifiers - Generally, they exist to control which parts of a class are internal implementation details (Or should be hidden away for whatever purpose), and which are the externally available components, by which other classes or other parts of the program may use the class.
Inheritance causes the entire base class to be inherited - including members to which the derived class has no access. It is entirely down to the public/protected interface of the base class to allow control over base class components.