Only instance data increases the size of instances of a class (in all implementations that I know of), except that if you add virtual functions or inherit from a class with virtual functions then you take a one-time hit for a v-table pointer.
Also, as someone else correctly mentions the minimum size of a class is 1 byte.
Some examples:
// size 1 byte (at least)
class cls1
{
};
// size 1 byte (at least)
class cls2
{
// no hit to the instance size, the function address is used directly by calling code.
int instanceFunc();
};
// sizeof(void*) (at least, for the v-table)
class cls3
{
// These functions are indirectly called via the v-table, a pointer to which must be stored in each instance.
virtual int vFunc1();
// ...
virtual int vFunc99();
};
// sizeof(int) (minimum, but typical)
class cls4
{
int data;
};
// sizeof(void*) for the v-table (typical) since the base class has virtual members.
class cls5 : public cls3
{
};
Compiler implementations may handle multiple virtual inheritance with multiple v-table pointers or other other methods, so these too will have effect on the class size.
Finally, member data alignment options can have an impact. The compiler may have some option or #pragma
to specify that member data should have a starting address that is a multiple of the number of bytes specified. For example, with alignment on 4 byte boundaries and assuming sizeof(int) = 4
:
// 12 bytes since the offset of c must be at least 4 bytes from the offset of b. (assuming sizeof(int) = 4, sizeof(bool) = 1)
class cls6
{
int a;
bool b;
int c;
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…