Ghost
Ghost

Reputation: 1835

Do private elements in the base class add to the size of the derived class?

// 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 ?

Upvotes: 1

Views: 883

Answers (5)

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

class base {
public:
  base(int v) : m_value(v) { }
  int value() { return m_value; }
private:
  int m_value;
};

class derived : private base {
  derived(int v) : base(v) { }
  int value2() { return value(); }
};

int main()
{
  derived d(2);
  return d.value2();
}

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:

struct A {
private:
  int i;
};

struct B {
  int j;
};

struct derived : A, B {
  int k;
};

An A object is laid out in memory as an int, and so is a B. A derived object could be laid out in memory as an A object, followed by a B object, followed by an int, which means it is a sequence of three ints. Whether the base class members are public or private doesn't affect that.

Upvotes: 2

cppguy
cppguy

Reputation: 3713

The private members are actually in the derived class, they're just not accessible within the derived class. The private keyword is to prevent programmers that derive from the base class from changing values the designer of the base class didn't want you to change because it might alter the functionality of the base class.

Have a look here for a deeper explanation

Fragile base class

Upvotes: 3

ltjax
ltjax

Reputation: 15997

Of course they are inherited -after all, the behavior of the base-class will probably depend on them being there-, they are just not accessible!

Upvotes: 1

user529758
user529758

Reputation:

Inherited methods of the base class can still use the private memebers. They have to be there.

Upvotes: 0

DanDan
DanDan

Reputation: 10562

Private members are inherited. You just cannot access them from your derived class.

Upvotes: 9

Related Questions