C++ object slicing vs polymorphism: after assigning a Derived to a Base reference, what does Display print?
#include
class CuriousTabBase {
int x;
public:
CuriousTabBase(int xx = 0) { x = xx; }
void Display() { cout << x; }
};
class CuriousTabDerived : public CuriousTabBase {
int y;
public:
CuriousTabDerived(int yy = 0) { y = yy; }
void Display() { cout << y; }
};
int main()
{
CuriousTabBase objBase(10);
CuriousTabBase &objRef = objBase;
CuriousTabDerived objDev(20);
objRef = objDev; // slicing assignment copies base subobject
objDev.Display();
return 0;
}
-
A0
-
B10
-
C20
-
DGarbage-value
-
EIt will result in a compile-time/run-time error.
Answer
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:
CuriousTabBaseandCuriousTabDerivedboth defineDisplay(), but it is not virtual.objBasestarts withx=10;objDevstarts withy=20and base part default-initialized (x=0due to base default constructor).- Assignment
objRef = objDevslices and copies only the base part (which is 0) intoobjBase.
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