Saturday, July 2, 2016

Object Slicing in C++ with example

What is Object Slicing? 
When an instance of derived class  is copied to base class object by value , part of members associated with derived object will be lost(sliced) . Here base class object discards the data related to the derived class because base class object don't have information about the derived members

When we copy derived obj by value to base obj,  the base class copy constructor /assignment operator will call (copy constructor will call at assigning object at the time of declaration (or) pass by value argument to function and assignment operator will call when assigning object after declarion), so base class don't have information about the derived members to copy.  This means the base copy/assignment will copy members related to base class only.

The following sample c++ code will explain the above description.