Gold mine of Visual C++ tricks!
How to Assert on Object Slicing?
![]()
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
{
public:
// 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.
| Print article | This entry was posted by Jijo Raj on March 11, 2009 at 6:21 pm, and is filed under C++. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
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)?
about 1 year ago
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!
Regards,
Jijo.
about 1 year ago
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.
about 1 year ago
I forgot to mention. If you deal with dynamically allocated polymorphic objects: Make the base class destructor either virtual or protected.
about 9 months ago
Without this constructor code won’t even compile. Why do we need any assertions?