devxlogo

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.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Seven Service Boundary Mistakes That Create Technical Debt

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.