C++ Interface

Started by
4 comments, last by Enigma 19 years, 4 months ago
I want to make a base strut for other struct's to inherit, but even though there are no variables, it has a size of 4 bytes... I'm just wondering if there is anyway to make this 0 bytes ( this struct will never be created since it has pure virtuals )
Advertisement
If it has virtual functions it needs a table to point to the functions as they get overriden in derived classes. It is likely that this is of size 4.
No, it is not possible for it to be 0 bytes. According to the standard, the minimum size for any type, even a completely empty one, must be at least 1 byte.

-bodisiw
-bodisiw
Also it's not possible to have an object of size zero. When you dereference an object you are in effect taking its address in memory. If it has zero size you can't take its address.

It is possible optimise when a base class is empty. See Empty Base Class Optimisation.

However this won't work for you if you have virtual functions.
Then is it possible to omit the 4 bytes when it is inherited?
Quote:Premature optimisation is the root of all evil.


I don't have a copy of the standard, so I can't guarantee that the following is accurate, but this is how I understand it:

A pure virtual base class with no member variables has a size of 4 bytes (not guaranteed by the standard, but all implementations seem to do it this way). This is the virtual function table pointer. This is not an overhead.

Imaging you have class Base, which is pure virtual and has no member variables, so it has a size of 4 bytes. You cannot instantiate an instance of Base. Now take a class Derived which inherits from Base and overrides the pure virtual function in Base with a concrete virtual function. It inherits the 4 byte virtual function table pointer since it requires it in order to work with class Base.

Every instantiated object derived from class Base must have this 4 byte overhead in order to work. Base does not require the 4 byte overhead but it is pure virtual, so it cannot be instantiated anyway. Therefore you can never have an instance that has a 4 byte overhead that is not required.

Enigma

This topic is closed to new replies.

Advertisement