R@M3$H.NBlog

Empty Class Size

28 September, 2013 - 3 min read

Why is the size of an empty class not zero?

To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects. Consider:

	class Empty { };

	void f()
	{
		Empty a, b;
		if (&a == &b) cout << "impossible: report error to compiler supplier";

		Empty* p1 = new Empty;
		Empty* p2 = new Empty;
		if (p1 == p2) cout << "impossible: report error to compiler supplier";
	}

There is an interesting rule that says that an empty base class need not be represented by a separate byte:

	struct X : Empty {
		int a;
		// ...
	};

	void f(X* p)
	{
		void* p1 = p;
		void* p2 = &p->a;
		if (p1 == p2) cout << "nice: good optimizer";
	}

This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this "empty base class optimization".

Size of an empty class is not zero. It is 1 byte generally. It is nonzero to ensure that the two different objects will have different addresses.

#include<iostream>
using namespace std;
class Empty { };
int main()
{
    Empty a, b;
    if (&a == &b)
      cout << "impossible " << endl;
    else
      cout << "Fine " << endl;
   return 0;
}

Output:

Fine

For the same reason (different objects should have different addresses), “new” always returns pointers to distinct objects. See the following example.

#include<iostream>
using namespace std;
class Empty { };
int main()
{
    Empty* p1 = new Empty;
    Empty* p2 = new Empty;
    if (p1 == p2)
        cout << "impossible " << endl;
    else
        cout << "Fine " << endl;
    return 0;
}

Output:

Fine

Now guess the output of following program (This is tricky)

#include<iostream>
using namespace std;
class Empty { };
class Derived: Empty { int a; };
int main()
{
    cout << sizeof(Derived);
    return 0;
}

Output (with GCC compiler. See this):

4

Note that the output is not greater than 4. There is an interesting rule that says that an empty base class need not be represented by a separate byte. So compilers are free to make optimization in case of empty base classes.

 

The size of the empty class is always ONE and not ZERO. This is because of below reasons

  1. Every object should have some address location to identify, independent of the no.of member variables in the class. Generally the size of the object is the sum of the member variables in the class. if no data is there, one byte of memory allocated to the object to identify. this will help to not conflicting with other empty objects.
  2. One more logical reason is that Some times we will use the sizeof() operator in division operation like X%sizeof(emptyclass) and if the value of empty class is zero , application/program will crash.

END