[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 113
  • Last Modified:

23. What is the size of an <empty> object?

23. What is the size of an <empty> object?
0
Nusrat Nuriyev
Asked:
Nusrat Nuriyev
  • 2
  • 2
4 Solutions
 
jkrCommented:
Give it a try ;o)

#include <iostream>

class Empty {

};

int main() {

  std::cout << "Size of Empty is " << sizeof(Empty) << std::endl;

  return 0;
}

Open in new window


VC++ says:
Size of Empty is 1
g++ says:
Size of Empty is 1
0
 
phoffricCommented:
>> Size of Empty is 1
But why 1? Why not 0? Could it be 0 on some other platform?
From: http://www.stroustrup.com/bs_faq2.html#sizeof-empty
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.
. . .
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";
	}

Open in new window

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".
BTW, from the link, you will find many other questions answered by one of the world's most authoritative authors on C++.
0
 
jkrCommented:
>>But why 1? Why not 0? Could it be 0 on some other platform?

That's why I formulated exactly like that ;o)

My initial idea would have been "implementation dependant". Yet the ones I had available were not enough to make a point, so thank you for shedding in some light.
0
 
phoffricCommented:
Those were my initial questions when I saw your result. So I looked to Stroustrup for an answer. Luckily I found it; otherwise, I would have to go through the wonderful C++ iso specification.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now