0
#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;
}

Since in c++ by default the members of class are private why does the sizeof derived class is 80.

3 Answers3

2

The access-specifier private is only related to the accessibility of the members of the base class in the derived class. The derived class contains the sub-objects of the classes it derives from. In this case, it contains b1 and b2 sub-objects. So its size is the sum of both their sizes.

P.W
  • 26,289
  • 6
  • 39
  • 76
2

Your line of argumentation is flawed. Privacy has nothing to do with sizeof a class.

Consider this example:

class base {
    int value = 42;
public:
    int get() { return value; } 
};

class derived : public base {};

The derived does inherit the get, it has no (direct) access to value, but of course in a derived instance there is the member value. You can easily convince yourself by calling get() on a derived ;)

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

derived inherits both b1 and b2, so its size is at least the sum of their sizes, each one of them being at least size of ten ints, 40 bytes with 32bit ints. Which gives us at least 80. Member visibility is not relevant here, it does not affect type's size. Apparently, arrays can't be optimized out for derived, being publicly a base (twice!), should contain exactly as many subobjects of type base—otherwise how would you upcast it to base?

bipll
  • 11,747
  • 1
  • 18
  • 32
  • i just thought that since it's a private variable it's not visible directly and it would just be stored with the base class. – Vineet Bhikonde Aug 31 '18 at 14:57
  • Yes, it is. It is a member of a subobject of base class, this subobject being a part of any instance of `derived`. – bipll Aug 31 '18 at 14:58