Alok
Alok

Reputation: 127

Why object size increases if class uses virtual inheritance?

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

Upvotes: 2

Views: 411

Answers (1)

TaQuangTu
TaQuangTu

Reputation: 2343

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

Upvotes: 3

Related Questions