Operator Overloading C++ (Object Oriented Programming).


                       Operator Overloading


  To familiarize students with operator overloading, overloading member and non-member functions



Turbo C++ IDE 

operator overloading


Writing C++ Program to perform following task
      Adding two objects using binary operator overloading

C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively. An overloaded declaration is a declaration that had been declared with the same name as a previously declared declaration in the same scope, except that both declarations have different arguments and obviously different definition (implementation). When we call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types you used to call the function or operator with the parameter types specified in the definitions.

Function overloading:

 we can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. 

Operator overloading:

 we can overload most of the built in operators available in C++. Thus a programmer can use operators with user-defined types as well. 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. Operator overloading can be as unary operator overloading or binary operator overloading. Overloading a single operator that involves one operand such as increment or decrement operators is called as unary operator overloading and overloading arithmetic operators which involves two operands is called as binary operator overloading. 

Binary operator overloading:

 operators that involved two operands such as arithmetic, comparison or arithmetic assignment operators are called as binary operator overloading. Binary operator overloading is very useful while adding two objects without passing as argument to a function. One parameter is used to inform compiler about binary operator overloading. 

Step 1: Create New C++ Program File and save it as lab7.cpp
Step 2: Write the following code as shown in figures below


binary operator overloading

Figure 23 (a): Binary operator overloading
Binary operator overloading
Figure 23 (b): Binary operator overloading
Binary operator overloading
Figure 23 (c): Binary operator overloading
Step 3: Save file again, compile and run it for required output as shown in figure below


 Binary operator overloading output

Figure 23 (d): Binary operator overloading

Post a Comment