How to Assert on Object Slicing?

11 03 2009

What is Object Slicing?
If derived object is assigned to Base object, then the derived object will be sliced off and only the base part will be copied. Indeed it will cause abnormalities. But is there any mechanism, atleast to assert while object slicing?

You can do it by adding an overloaded constructor for derived in Base class and then assert in it. For instance,

// Forward Declaration.
class Derived;

// Base class.
class Base
    // Default Constructor.
    Base() {}
    Base( Derived& derived ) { ASSERT( FALSE ); }

// Derived class.
class Derived

// Test code.
Base ObjBase;
Derived ObjDerived;

ObjBase = ObjDerived;

Take care that it won’t work for passing pointer and reference. But still good enough. nah?

Targeted Audiance – Intermediate.