In C++ object layout, is the size of a derived-class object always equal to the sum of the sizes of the base-class data members and the derived-class data members? Choose the most accurate evaluation.

Difficulty: Medium

Correct Answer: Incorrect — padding, alignment, virtual pointers, and base-subobject layout can change the total size.

Explanation:


Introduction / Context:
This question asks about C++ object memory layout. While it is tempting to assume sizes add linearly, real-world layouts are constrained by alignment, padding, vtable pointers for polymorphic classes, empty-base optimizations, and ABI rules that frequently make the size differ from a simple sum of member sizes.


Given Data / Assumptions:

  • Classes may have base classes and their own members.
  • Compilers must respect alignment requirements for each member type.
  • Polymorphic classes (with virtual functions) often store an implementation-defined vptr.


Concept / Approach:
The size of an object is influenced by: (1) alignment of the largest member; (2) padding between members to satisfy alignment; (3) potential padding at the end (tail padding); (4) base-subobject layout rules; and (5) implementation details such as a vptr. Therefore, the total size may be larger than the numerical sum of member sizes, and in some cases EBO (empty base optimization) can even reduce overhead for empty bases.


Step-by-Step Solution:

Consider Base with members requiring 8-byte alignment; Derived adds a 4-byte member. Compiler may insert padding to keep alignment → size exceeds raw sum. If virtual functions exist, a vptr (pointer-sized) is added per most ABIs.


Verification / Alternative check:
Using sizeof(Derived) vs the arithmetic sum of sizeof individual members demonstrates differences across platforms (32-bit vs 64-bit) and compilers, proving it is not a strict sum rule.


Why Other Options Are Wrong:

  • Always exact sum: contradicted by padding and vptr.
  • Only non-virtual classes: even then, alignment/padding applies.
  • Public vs protected/private inheritance has no effect on size rules.
  • Optimization level does not change object layout guarantees required by the ABI.


Common Pitfalls:
Ignoring alignment requirements; assuming access specifiers affect memory; or forgetting vptr presence for polymorphic classes.


Final Answer:
Incorrect — padding, alignment, virtual pointers, and base-subobject layout can change the total size.

More Questions from Inheritance

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion