2 minutes
Operator Overloading
Operator overloading is a way to make an operator work in different ways based on types of operants.
Some Rules about Operator overloading :-
-
New operators can not be created.
-
Precedence and associativity of the operators cannot be changed.
-
Overloaded operators cannot have default arguments except the function call operator ().
-
Operators cannot be overloaded for built in types only. At least one operand must be used defined type.
-
Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must be defined as member functions
-
Except the operators in above point, all other operators can be either member functions or a non member functions.
-
Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.
-
operators ‘.’ , ‘::’, ‘?:’, ‘sizeof’.
-
Any constructor that can be called with a single argument can act as a convesion operator and hence can implicitly convert.
-
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:
- A constructor to either make an initial allocation or set the pointer to NULL.
- A destructor to delete the dynamically allocated memory.
- A copy constructor to make a copy of the dynamically allocated memory.
- An overloaded assignment operator to make a copy of the dynamically allocated memory.