Operator overloading is a way to make an operator work in different ways based on types of operants.

Some Rules about Operator overloading :-

  1. New operators can not be created.

  2. Precedence and associativity of the operators cannot be changed.

  3. Overloaded operators cannot have default arguments except the function call operator ().

  4. Operators cannot be overloaded for built in types only. At least one operand must be used defined type.

  5. Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must be defined as member functions

  6. Except the operators in above point, all other operators can be either member functions or a non member functions.

  7. Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.

  8. operators ‘.’ , ‘::’, ‘?:’, ‘sizeof’.

  9. Any constructor that can be called with a single argument can act as a convesion operator and hence can implicitly convert.

  10. some operator for eg =,+=,-=,etc has to be non-static member functions;

className operator + (const className &){

}

Operator overloading is just like function overloading with difference being instead of function name we use operator ‘symbol’

Assignment Operator

ClassName & operator = (const ClassName &obj){

  if( this != &obj ) // see how we are comparing address 
  {

  }

  return *this;
}

Remmber to check self equality check in assignment operator overloading.

If we don’t check self assignment then we may have undifined behaviour in cases like when we are deallocating memory from current object.

It recommended to return non-const reference from a assignment operator through it can be anything(may be a void but then a=b=c would’t work)

The reason to return non const reference is that is a requirement for “Assignable” in the standard.

So if we return a const reference than we can not do stuff like

(a=b).non_constant_function

or 

(a=b)=c;

Deep Copy vs Shallow copy

In shallow copy, All the member field values are copied. This works good if fields are values but if fields are pointer pointing to dynamically allocated memory then pointer will get copied but not the dynamically allocated memory.

Hence both, original and copied pointer, will point to same dynamic memory.

In deep copy, dynamic allocated memory is also copied.

Default copy constructor and assignment operator create shallow copy.

A class that requires deep copies generally needs:

  1. A constructor to either make an initial allocation or set the pointer to NULL.
  2. A destructor to delete the dynamically allocated memory.
  3. A copy constructor to make a copy of the dynamically allocated memory.
  4. An overloaded assignment operator to make a copy of the dynamically allocated memory.