While going through virtual base classes, i got to know that to avoid ambiguity and to save space we use virtual base classes. I checked this concept with simple program as shown below in CodeBlocks
#include <iostream>
using namespace std;
class A
{
public:
int a;
};
class B : public virtual A
{
public:
int b;
};
class C : public virtual A
{
public:
int c;
};
class D: public B, public C
{
public:
int d;
};
int main()
{
cout<<"sizeof(int) "<<sizeof(int)<<endl;
cout<<"sizeof(A) "<<sizeof(A)<<endl;
cout<<"sizeof(B) "<<sizeof(B)<<endl;
cout<<"sizeof(C) "<<sizeof(C)<<endl;
cout<<"sizeof(D) "<<sizeof(D)<<endl;
return 0;
}
got output as:
sizeof(int) 4
sizeof(A) 4
sizeof(B) 12
sizeof(C) 12
sizeof(D) 24
i understood the logic behind the first 4 lines of output, but i can't understand why sizeof(D) 24 , it should be 4(int d) + 4(int c) + 4(int b) + 4(int a) + 4(because of some virtual base pointer) = 20. Here 'a' is inherited only once because of virtual base classes and hence i should have get 20 as sizeof(D) but it is 24.
someone please analyse and help me...
Look at the code size of B is 12 and size of C is 12 so D inherits everything from B and C so depending on compiler and C++ versions, most of them just go the size of D is B+C or namely 24. But not every compiler does the same, so we cannot make any conclusion unless we know your C++ version and compiler version and IDE makes a big difference too..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.