Most of us are aware that the size of object of an empty class is 1 byte( It is !! ). Have you ever thought why it is so? It is implemented likewise to ensure that the addresses of two different objects will be different. For the same reason, "new" for an empty class always returns pointers to distinct objects. For example :
class Empty { };
void f()
{
Empty a, b;
if (&a == &b) cout << "Change your object concepts";
Empty* p1 = new Empty;
Empty* p2 = new Empty;
if (p1 == p2) cout << " Which new is this?? ";
}
There is another 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 << "Well, the base class has no bytes";
}
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".
No comments:
Post a Comment