Skip to content
Tags

Empty class – not so empty

July 16, 2013

Conclusion:

1. Both g++ and msvc implemented base class optimizations.

2. MSVC does a better job than g++ with respect to empty base class optimization when base class is derived class as well

#include <iostream>

//A virtual base class subobject occurs only once in the derived class regardless of the number of times it occurs within the class inheritance hierarchy.
//Static data members are maintained within the global data segment of the program and do not affect the size of individual class objects.
class X {};
class Y : public virtual X {};
class Z : public virtual X {};
class A : public Y, public Z {};

class Y1 : public X {};
class Z1 : public X {};
class A1 : public Y1, public Z1 {};

class Y2 {};
class Z2 : public X {};
class A2 : public Y2, public Z2 {};

int main() {
using namespace std;
cout << “virtual inheritance” << endl;
cout << “sizeof(X) : ” << sizeof(X) << endl;
cout << “sizeof(Y) : ” << sizeof(Y) << endl;
cout << “sizeof(Z) : ” << sizeof(Z) << endl;
cout << “sizeof(A) : ” << sizeof(A) << endl;

cout << endl << “non virtual inheritance” << endl;
cout << “sizeof(X) : ” << sizeof(X) << endl;
cout << “sizeof(Y1) : ” << sizeof(Y1) << endl;
cout << “sizeof(Z1) : ” << sizeof(Z1) << endl;
cout << “sizeof(A1) : ” << sizeof(A1) << endl;

cout << endl << “non virtual inheritance 2” << endl;
cout << “sizeof(X) : ” << sizeof(X) << endl;
cout << “sizeof(Y2) : ” << sizeof(Y2) << endl;
cout << “sizeof(Z2) : ” << sizeof(Z2) << endl;
cout << “sizeof(A2) : ” << sizeof(A2) << endl;
return 0;
}

 

Output:

Cygwin g++

$ ./a.exe
virtual inheritance
sizeof(X) : 1
sizeof(Y) : 4
sizeof(Z) : 4
sizeof(A) : 8

non virtual inheritance
sizeof(X) : 1
sizeof(Y1) : 1
sizeof(Z1) : 1
sizeof(A1) : 2

non virtual inheritance 2
sizeof(X) : 1
sizeof(Y2) : 1
sizeof(Z2) : 1
sizeof(A2) : 1

 

Output

MSVC cl.exe

$ ./empty.exe
virtual inheritance
sizeof(X) : 1
sizeof(Y) : 4
sizeof(Z) : 4
sizeof(A) : 8

non virtual inheritance
sizeof(X) : 1
sizeof(Y1) : 1
sizeof(Z1) : 1
sizeof(A1) : 1

non virtual inheritance 2
sizeof(X) : 1
sizeof(Y2) : 1
sizeof(Z2) : 1
sizeof(A2) : 1

 

and linux g++ 64bits

$ ./a.out
virtual inheritance
sizeof(X) : 1
sizeof(Y) : 8
sizeof(Z) : 8
sizeof(A) : 16

non virtual inheritance
sizeof(X) : 1
sizeof(Y1) : 1
sizeof(Z1) : 1
sizeof(A1) : 2

non virtual inheritance 2
sizeof(X) : 1
sizeof(Y2) : 1
sizeof(Z2) : 1
sizeof(A2) : 1

From → Uncategorized

Leave a Comment

Leave a comment