Tuesday, November 29, 2011

Assignment between Class Objects

Some short notes about assignment between class objects.

Suppose we are considering the assignment a = b, where a if of class A type, and b is of class B type.
  1. The overloaded operator= function will be looked first. If there is any, the assignment will call this function.

  2. If no overloaded operator= function, and a and b are of same class type, the assignment will be member-wise shallow copy.

  3. If no overloaded operator= function, and class B is derived from class A (in other words, b is an a), the assignment will copy the base class members.

  4. If no overloaded operator= function, and a and b are of unrelated class types, the assignment will try to call copy constructor if any.

  5. If no overloaded operator= function, a and b are of unrelated class types, and no copy constructor available, the assignment will try to call overloaded type casting function if any.

  6. If none of above applies, then the compiler will report an error about the assignment.

Related Posts:
Type Casting in C++
Type Casting on Classes
static_cast, dynamic_cast, and reinterpret_cast

No comments:

Post a Comment