2

In the following code:

#include <iostream>

class a {
    char a;
};

class b : virtual public a {
    char b;
};

class c : virtual public a {
    char c;
};

class d : public b, public c {
    char d;
};

int main() {
    std::cout << "sizeof a: " << sizeof(a) << std::endl;
    std::cout << "sizeof b: " << sizeof(b) << std::endl;
    std::cout << "sizeof c: " << sizeof(c) << std::endl;
    std::cout << "sizeof d: " << sizeof(d) << std::endl;
    return 0;
}

the output is:

sizeof a: 1
sizeof b: 16
sizeof c: 16
sizeof d: 32

I want to know why the increased size is 16. size of char is 1 that means increased size is 15. I know that virtual class needs a pointer for its offset that adds 4 bytes then 11 bytes does not make any sense. Can anyone explain why does it happen, my question is different as it is a diamond inheritance case

Alok
  • 127
  • 1
  • 7
  • 4
    Is the code actually compiled for 32 bit? Compiled for 64 bit, a pointer is 8 bytes, with 8 byte alignment, so you'd need 7 bytes of padding to fill out the structure, which would get your observed 16 bytes. – ShadowRanger Jun 02 '18 at 12:41
  • 1
    yes the code is for 64 bit, okay then this explains 16 bit – Alok Jun 02 '18 at 12:53
  • 1
    Possible duplicate of [Do class methods increase the size of the class instances?](https://stackoverflow.com/q/8058213/608639), [C++ object size with virtual methods](https://stackoverflow.com/q/2038717/608639), [Why does virtual keyword increase the size of derived a class?](https://stackoverflow.com/q/10903596/608639), etc. – jww Jun 02 '18 at 13:57

1 Answers1

3

Virtual inheritance is used to solve the Diamond problem in multiple inheritance.

Virtual inheritance will create a vtable pointer in each object of child class.

It makes size of child class object increase and the increase size depend on your operating system where your code complied. May be your code has been complied in OS 64-bit so size of the vtable pointer is 8 bytes. But you wonder why sizeof(b) = 16. The answer is Memory alignment mechanism. you can reference to below link to know more about what I say and sorry for my bad English grammar.

Memory alignment and padding:

http://www.cplusplus.com/forum/articles/31027/

Virtual inheritance:

https://www.cprogramming.com/tutorial/virtual_inheritance.html

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30
  • Also see [Do all classes have a Vtable created for them by the compiler?](https://stackoverflow.com/q/5709892/608639), [Does every class have virtual function table in C++](https://stackoverflow.com/q/9477145/608639), etc. – jww Jun 02 '18 at 14:01