// inheritence experiment
#include"stdafx.h"
#include<iostream>
using namespace std;
class base
{
private:
int i;
};
class derived: public base
{
private:
int j;
};
int main()
{
cout << endl << sizeof(derived) << endl << sizeof(base);
derived o1;
base o2;
cout << endl << sizeof(o1) << endl << sizeof(o2);
}
I’m getting this output:
8
4
8
4
why’s that so? private data members of a base class aren’t inherited into the derived class, so why I am getting 8 bytes for both, the size of derived and o1 ?
How do you expect this to work if the private base class doesn’t store the value somewhere?
Your choice of words “inherited into the derived class” makes me think you are confused about how inheritance works. Members from the base class are not inherited into or copied into the derived class. The derived class contains an instance of the base type, as a sub-object within the complete derived object, so a derived class is (usually) at least as large as the sum of its base classes.
Consider this code:
An
Aobject is laid out in memory as anint, and so is aB.A
derivedobject could be laid out in memory as anAobject, followed by aBobject, followed by anint, which means it is a sequence of threeints. Whether the base class members are public or private doesn’t affect that.