Operator Overloading in C++

Operator Overloading in C++

Operator overloading is a type of polymorphism supported by C++. Operator overloading allows us to redefine the operation of the basic operators to be applied on user-defined classes and data types.

For example if we have defined a class and there are two objects of this class, then we might like to do an operation like below.

object1 + object2

The default behavior of + operator does not allow us to use + operator for this purpose. But C++ allows us to redefine + operator to perform the intended operation. Similarly, we might like to store the result of above operation in another object of the class as below.

object3 = object1 + object2

In the above expression apart from + operator, = operator is used to store the result of operation in object3. Again + operator does not allow us to do so but can be redefined to achieve the above intended objective.

The following example shows that how + and = operators can be overloaded to achieve the objective discussed above.

following example shows

We can see that + operator is declared for overloading at line 9 and = operator is declared for overloading at line 10. The = operator is overloaded in lines 12 to 18 and + operator is overloaded in lines 19 t 25. The + operator is redefined to add the corresponding data members of two objects of the same class and = operator is redefined to store the (calculated) data members to another object of the same class. The following code shows that how that how to make use of the above code.

how to make use of the above code

The overloaded + and = operators are used at line 40 producing the following output.

output

From the above output it is clear that + operator is redefined to add the data members of two objects of Box class and = operator is redefined to store the result in another object of Box class.

More Related Articles For You

    C++ Tutorial

    C++ Quizzes