0

Can anyone explain, why size of the objC is 8, not 12?

I think, that if it in the class C I have object with type int and in A, B - char, then after creation of the objC it should be 4 bytes for objA, objB and ObjC.

class A {
    char a;
};

class B : A {
    char b;
};

class C : B {
    int c;
};

int main()
{
    A objA;
    B objB;
    C objC;

    cout << sizeof(objA) << endl; // 1
    cout << sizeof(objB) << endl; // 2
    cout << sizeof(objC) << endl; // 8! Why not 12?

    return 0;
}

Edit 1:

In this case sizeof(objC) will be 12:

class A {
    char a;
};

class B : A {
    int b; // Here is int
};

class C : B {
    char c; // Here is char
};
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
Amazing User
  • 3,473
  • 10
  • 36
  • 75

2 Answers2

4

I believe that class C will have:

  • 2x 1-byte chars
  • 2-bytes of padding, so the int starts on a 4-byte boundary.
  • 1x 4-byte integer
  • Making a total of 8-bytes

To keep the integer aligned on a boundary, there'll be 2-bytes of padding, making 8 bytes.

How do you get 12??


In your second example, class C will have:

  • a 1-byte char.
  • 3-bytes of padding before the int. (keep the int on a 4-byte boundary)
  • a 4-byte int.
  • a 1-byte char.
  • Making a total of 9-bytes.

Sizes are rounded up to the nearest 4-bytes, which is 12.

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • The OP probably got 12 by assuming that classes A and B would both be aligned to a 4-byte boundary before being considered part of the subclasses that inherit them. So 4+4+4 = 12. – lurker Oct 22 '15 at 19:55
  • 2
    "Sizes are rounded up to the nearest 4-bytes" - not true in general, e.g `sizeof(objA)` in OPs code is `1`. ITYM that the struct size is usually rounded up to a multiple of the alignment of its most-aligney member, so that an array of such structs works. – M.M Oct 22 '15 at 19:55
  • 1
    @M.M "Most-aligney member", I'm going to have to keep that term in mind! – Barry Oct 22 '15 at 19:59
  • @Barry hmm..please don't :) – M.M Oct 22 '15 at 20:00
2

In the first case, there is one padding. In the second case there are two paddings.

The first case will be:

+---+---+---+---+---+---+---+---+
| a | b |   |   |     c         |
+---+---+---+---+---+---+---+---+
<-     4      ->|<-    4      ->|

The second case will be:

+---+---+---+---+---+---+---+---+---+---+---+---+
| a |   |   |   |     b         | c |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+
<-     4      ->|<-    4      ->|<-    4      ->|
R Sahu
  • 204,454
  • 14
  • 159
  • 270