C++ Operator Overloading

October 27, 2015 Posted by WithU Technologies
In case of Operator Overloading we overload operator to use the operator with user defined types.

For Example: ‘*’ multiplication operator can be overloaded to add two objects together.

In C++ Except five operators, all other Operators can be overloaded. And the five Operators which can’t be overloaded are:

1.       sizeof – size of Operator

2.       :: - Scope Operator

3.       .  - Member Selector

4.       ?: - Ternary operator

5.       * - Member Pointer selector

Syntax:

ReturnType ClassName operator(keyword) operator(symbol)(parameter list)

{

//Function body

}

Example:

#include<iostream>
using namespace std;

class NewOperator{

public:

      int Out;  //initialised a variable as a public member to make it accessible by all other members

      NewOperator()    //Blank Constructor is initialized, without any parameter

      {

      }

      NewOperator(int a)   //Another constructor initialized along with one parameter

            :Out(a)    //Member initilaizer list and here Out is the variable and a is the value assign to it

            {

            }

          NewOperator operator*(NewOperator &NewOb){  // Operator * means we multiply the overloaded operators

            NewOperator result;                  // A new Object result is created

            result.Out=this->Out+NewOb.Out; //this act as a pointer to the object which refers to the current object and NewOb is parameter's object



            return result;   // result is returned

      }

};

int main(){

      int r;    //local variable initialized

      int s;    //local variable initialized

      cout<<"Enter a number: "<<endl;   //Take an input

      cin>>r;

      cout<<"Enter another number: "<<endl;  //Take another input

      cin>>s;

      NewOperator DisplayOut = r+s;   //New object created which stores the summation of two values

      cout<<"Output: "<<DisplayOut.Out;   //Display the output by calling member variable Out

}

/*

 * Enter a number:

12

Enter another number:

143

Output: 155

 */
·         We declare two constructors with the same class name and one-member variable.

·         Overloaded operator are functions and thus they have return type and parameter list.

·         There we use the keyword operator after the class name and then the keyword operator is followed by an operator symbol which is to be overloaded.

·          Here we overload the multiplication operator (*).

·         The parameter takes an object of our class and it will also return the same.

·         Thus the result’s object Out member variable holds the summation of current object pointed by this keyword and the parameter object. It returned the result object.


·         Precedence, grouping or number of operands of an operator cannot be changed.

·         Only existing operators can be overloaded.