Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

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