0

Why sizeof is increased for virtual inheritance

Refer code below: Why D1 has 56 size ? Due to virtual inheritance, only one copy of class A will be there resulting 10*4 = 40 bytes. What's these extra 16 bytes? Why D has 88 size? Due to B and C both not virtually inheriting, two copy of A class will be there and hence 2 * 10 * 4 = 80. Why these extra 8 bytes? https://sololearn.com/compiler-playground/cnaC3aT2jj6N/?ref=app

15th Jun 2024, 5:58 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Antworten
0
Surprising this question has no answer yet. I thought it is very basic and I might be missing something
17th Jun 2024, 11:12 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Please note that this answer may be inaccurate. I don't have any useful quotes from the C++ standard, but as I recall, the C++ standard did not say much about the in-memory representation of objects of types that contain virtual inheritance. So let us consider how one implementation achieves virtual inheritance. Within a member function of B, we need to somehow access member subobjects in A from a pointer to B. However, A is inherited virtually, and it depends on the situation whether the member subobjects in A are located in memory consecutively before the member subobjects in B in the object pointed to by this; It depends on whether B is the only class in which a type inherits that has virtual inheritance from A. However, we want to have only one number of member function implementations of B. So, in order to make the same member function work in both cases, there is a pointer in B that points to A.
7th Aug 2024, 8:36 AM
fuseDestroyer
fuseDestroyer - avatar