oops · medium
Object Slicing
When a Derived object is copied into a Base by value, only the Base subobject is copied — the extra Derived members are 'sliced off', and Base's copy constructor sets the vptr to Base's vtable. Virtual calls on the slice therefore dispatch to Base, silently losing polymorphism. Binding a Base& or Base* to the object copies nothing and keeps the Derived vptr, so virtual dispatch still reaches Derived. Rule: handle polymorphic objects through references or pointers, not by value.
Object slicing: copying a Derived into a Base BY VALUE keeps only the Base subobject and resets the vptr to Base, so virtual calls lose polymorphism. Pass polymorphic types by reference or pointer.
The code
struct Base { int id; virtual void speak();};struct Derived : Base { double extra; void speak() override;};
Derived d;Base b = d; // BY VALUE: copies only the Base subobjectb.speak(); // -> Base::speak (Derived part is gone)
Base& r = d; // BY REFERENCE: no copy, full objectr.speak(); // -> Derived::speak (polymorphic)What this lesson walks through
- 01
- 02
- 03
- 04
- 05
- 06
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Object Slicing and 100+ animated C++ interview lessons.