Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: C++
Expertise: Beginner
Oct 26, 1999



Application Security Testing: An Integral Part of DevOps

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
    int year, month, day;
    virtual void Display() const; //output mm-dd-yy
  class DateTime: public Date
    int hrs, min, sec; // additional members; might be sliced off
    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.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date