Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

inheritance - Is C++ allowed to increase the derived class size if there're no new member variables compared to the base class?

Suppose I have a base class with some member variables and no virtual functions:

class Base {
   int member;
};

and a derived class that derives in a non-virtual way from Base and has no new member variables an again no virtual functions:

class Derived : Base {
};

Obviously sizeof(Derived) can't be smaller than sizeof(Base).

Is sizeof(Derived) required to be equal to sizeof(Base)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From 5.3.2 [expr.sizeof]

When applied to a class, the result [of sizeof] is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. The size of a most derived class shall be greater than zero (1.8).

From 1.8 [intro.object]

Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. An object of POD type (3.9) shall occupy contiguous bytes of storage.

and a note:

The actual size of a base class subobject may be less than the result of applying sizeof to the subobject, due to virtual base classes and less strict padding requirements on base class subobjects.

Put these together and I think what it's telling you is that you have no guarantees whatsoever as to what sizeof might tell you, other than the result will be greater than zero. In fact, it doesn't even seem to guarantee that sizeof(Derived) >= sizeof(Base)!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...