Consider the following inheritance:
class Base {
protected:
Base() { }
public:
double Multiply(double x);
};
class Derived : public Base {
double _value;
public:
Derived(double init) : _value(init) { }
double Multiply(double x) { return x*_value; }
};
This code piece is to be used in templated codebase. Polymorphism is not an option because it adds VTable pointer thus doubles the memory consumption.
However, I suspect that because of C++ requirement for objects to have size at least 1 byte, the size of Derived
would become 9 bytes and, consequently, because of padding/alignment it will further become 16 bytes.
So is there a way in C++ to keep the size of Derived
equal to the size of double
(usually 8 bytes) ?
What does the standard say about the size of Derived
?
Particularly, how does MSVC++ behave in this case?
This is called Empty base optimization, it is defined in standard as following:
In your example inheriting
Base
class does not affect the size of theDerived
class. However MSVC++ performs such optimization only for a first empty base class so inheriting from addition empty base classes will lead to growth ofDerived
class size. I believe this has been a point of critisim towards MSVC++ for a long time, as many other compilers don't have this issue. This can be really troublesome if you have a lot of small auxiliary classes. As a workaround a deriving template base class could be used to convert multiple inheritance into a chain of single inheritance:MS Connect bug page. It looks like they aren't aiming to fix it after all.