C++ object slicing vs polymorphism: after assigning a Derived to a Base reference, what does Display print?\n\n#include<iostream.h>\nclass CuriousTabBase {\n int x;\npublic:\n CuriousTabBase(int xx = 0) { x = xx; }\n void Display() { cout << x; }\n};\nclass CuriousTabDerived : public CuriousTabBase {\n int y;\npublic:\n CuriousTabDerived(int yy = 0) { y = yy; }\n void Display() { cout << y; }\n};\nint main()\n{\n CuriousTabBase objBase(10);\n CuriousTabBase &objRef = objBase;\n\n CuriousTabDerived objDev(20);\n objRef = objDev; // slicing assignment copies base subobject\n\n objDev.Display();\n return 0;\n}

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).
  • Assignment 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

More Questions from References

Discussion & Comments

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