Operator Overloading in C++

We can redefine or overload most of the built-in operators available in C++. Thus a programmer can use operators with user-defined types as well, this process is operator overloading.
Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);

declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows:

Box operator+(const Box&, const Box&);

Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below:

OUTPUT:

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Following is the list of operators which can be overloaded:
+ * / % ^
& | ~ ! , =
< > <= >= ++
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
Following is the list of operators, which can not be overloaded:
:: .* . ?:

Leave a Reply