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:
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:
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.
Discussion & Comments