Beware of Object Slicing

Beware of Object Slicing

Passing a derived object by value to a function that takes a base object by value may cause a problem known as “object slicing”; every additional data member declared in the derived object is omitted. The resultant object contains only the data members declared in the base class. Furthermore, the dynamic binding mechanism is inoperative in this case:

   class Date  {  private:    int year, month, day;  public:    virtual void Display() const; //output mm-dd-yy    };  class DateTime: public Date  {  private:    int hrs, min, sec; // additional members; might be sliced off  public:    void Display() const; // output mm-dd-yy hh:mm:ss  };  void f(Date b)   // pass by value  {    b.Display(); // no dynamic binding; calls Date::Display()  }int main(){  DateTime dt;  f(dt);   // dt is sliced}

Object slicing may result in undefined behavior. Therefore, you should avoid passing an object by value when possible.


Share the Post: