Difficulty: Medium
Correct Answer: 20
Explanation:
Introduction / Context:
This question contrasts object slicing with dynamic dispatch. The assignment objRef = objDev;
slices, copying only the base subobject from objDev
into objBase
. The call that follows is made on objDev
(a separate object), not through the base reference.
Given Data / Assumptions:
CuriousTabBase
and CuriousTabDerived
both define Display()
, but it is not virtual.objBase
starts with x=10
; objDev
starts with y=20
and base part default-initialized (x=0
due to base default constructor).objRef = objDev
slices and copies only the base part (which is 0) into objBase
.
Concept / Approach:
Slicing does not affect the distinct objDev
object's y
. The subsequent call objDev.Display()
is a direct call to the derived version, printing y
= 20.
Step-by-Step Solution:
1) Construct objBase(10)
⇒ base.x=10. 2) Construct objDev(20)
⇒ derived.y=20, base.x=0 (base default constructor). 3) objRef = objDev
copies only base.x (0) from objDev
into objBase
. 4) objDev.Display()
calls the derived method (non-virtual but chosen by static type CuriousTabDerived
), printing 20.
Verification / Alternative check:
If the final call were objRef.Display()
, it would print 0 (the sliced base x). Making Display()
virtual would enable dynamic dispatch through base references.
Why Other Options Are Wrong:
0/10: These would correspond to calling the base Display()
on the sliced object, not the derived object's method. Garbage/error: All objects are well-formed; there is no UB here.
Common Pitfalls:
Confusing slicing effects on one object with the independent state of another; assuming virtual dispatch when methods are not declared virtual
.
Final Answer:
20
Discussion & Comments