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.



5 responses

12 03 2009

Hi there,

This is interesting. But will work only if “Derived” is known at the time of writing “Base”. Usually you will not know who will derive when you write a base class.

How about making the base class copy protected (private copy constructor)?

12 03 2009

Hi Navaneeth,

Yes. its true if the base class is part of framework, where all derived classes are not known. But, the idea of private constructor is great! I’ll update it in the article. Thanks a lot for sharing it and Keep watching!


12 03 2009

public inheritence is kind of overused. It really only models the “is-a” relationship well and nothing else. public inheritence is what you use for runtime polymorphism. If runtime polymorphism is what you want, consider using smart pointers to manage the objects. Also, make the “interface” base class an abstract class — preferably without data members. If the base class is abstract you won’t be able to define variables of type base — only pointers or references. This will save you from slicing problems.

12 03 2009

I forgot to mention. If you deal with dynamically allocated polymorphic objects: Make the base class destructor either virtual or protected.

6 12 2009

Without this constructor code won’t even compile. Why do we need any assertions?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: