Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why base classes can have a zero size?

Tags:

c++

Basically it is a follow up of this question..

When I look into the Standard docs I found this..

In Classes 9.3,

Complete objects and member subobjects of class type shall have nonzero size.96) ...

Yeah, true.. But,

96)Base class subobjects are not so constrained.

So, when I looked into Stroustrup's FAQ, there is an example as

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

My question is I couldn't understand how it is an optimization and also why base classes are allowed to have zero size?

like image 903
liaK Avatar asked Oct 12 '10 10:10

liaK


2 Answers

Base classes cannot have zero size. Only base class subobjects can. Meaning the base part of the derived object.

like image 131
Armen Tsirunyan Avatar answered Oct 09 '22 18:10

Armen Tsirunyan


If the base class is empty, you will never need to have the base class object's or any of its members' address (independent of the derived class objects's address, that is), so it is legal to optimize its size away.

That saves you (at least) one byte of memory (can be more due to memory alignment rules), which can add up to significant savings if you have millions of such objects in your app on a memory-constrained platform.

like image 33
Péter Török Avatar answered Oct 09 '22 20:10

Péter Török