Search This Blog

Saturday, November 14, 2009

C++, Base Class Copy Constructor And Assignment Operator

In the derived class, when defining copy constructor and (copy) assignment operator:
  • Copy constructor: remember to call base(rhs) in the initialize list.
  • Assignment Operator: remember to call base::operator=(rhs) inside if (this =! &rhs)
Why we need to do this?
  • compiler will use the default constructor and default assignment operator. it turns out they do not initialize the base part properly and do not assign new value.
  • derive class cannot access the private stuff in the base class, therefore we need public copy constructor and public (copy) assignment operator to deal with the base class subobject.

Effective C++, copy all parts of an object.

No comments: