C++ Operator overloading

An operator is a symbol that tells the compiler to perform some specific Logical or mathematical or calculations. C++ contains a lot of in built-in operators that carries operations like Arithmetic, Logical, relational etcThe meaning of an operator is always same for variable of basic types like: int, float, double etc. For example: To add two integers, + operator is used. However, for user-defined types (like: objects), you can redefine the way operator works.
 
For example: If there are two objects of a class that contains string as its data members. You can redefine the meaning of + operator and use it to concatenate those strings.
 
In C++ we can redefine the use of operator which we call operator overloading. The mechanism of giving additional meaning to the normal C++  operators like (+,-,*,++,etc.) when they are applied to the user defined data type without changing their original meaning is called operator overloading
.
Operator overloading is an important OOP  concept. It is a type of polymorphism in which an operator is overloaded to provide user defined meaning to it. Overloaded operator is used to perform operation on user-defined data type.
C++ Operators that can be overloaded:
  • Unary operators(+,-,++,–)
  • Arithmetic operators(+,-,*)
  • Relational operators(<,>,==,<=,>=,!=)
  • DMA operators(new, delete)
  • Function call operator: ()
  • Array element reference:[]
  • Input/output operators(<<,>>)
C++ Operators that can’t be overloaded:
  • Class member access operators:(.,*.)
  • Scope resolution operator:(::)
  • Size of operator: (sizeof)
  • Conditional operator: (?:)

The reason why we cannot overload these operators may be attributed to the fact that these operators take names (example class name) as their operand instead of values, as in the case with other normal operators.

How to overload operators in C++ programming?

To overload an operator, a special operator function is defined inside the class as:

class className

{

    … .. …

    public

       return_Type operator operator_symbol(arguments)// operator function declaration

       {

           … .. …

       }

    … .. …

};

return_type class_Name:: operator operator_symbol(arguments) // definition of operator function

{

…… ….. ….

}//function body

  • Here, return_Type is the return type of the function.
  • The return_Type of the function is followed by operator keyword.
  • operator_symbol is the operator symbol you want to overload. Like: +, <, -, ++
  • You can pass arguments to the operator function in similar way as functions.
Invoking(calling) overloaded operator function:
  • For unary operator: op x or x op (x is object and op is symbol of overloaded operator e.g. ++X or X++)
  • For binary operator: x op y (object1 operator_symbol object2 e.g. X+Y)                       
    • OR, x.operator op(y) for member function   
    • OR, operator op(x,y) for friend function

Example: Operator overloading in C++ Programming

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Test
  5. {
  6. private:
  7. int count;
  8.  
  9. public:
  10. Test(): count(5){}
  11.  
  12. void operator ++()
  13. {
  14. count = count+1;
  15. }
  16. void Display() { cout<<“Count: “<<count; }
  17. };
  18.  
  19. int main()
  20. {
  21. Test t;
  22. // this calls “function void operator ++()” function
  23. ++t;
  24. t.Display();
  25. return 0;
  26. }

Output

Count: 6

Explanation:

This function is called when ++ operator operates on the object of Test class (object t in this case).

In the program, void operator ++ () operator function is defined (inside Test class).

This function increments the value of count by 1 for t object.

Rules for the operators overloading:
  1. Operator overloading allows you to redefine the way operator works for user-defined types only (objects, structures). It cannot be used for built-in types (int, float, char etc.).
  2. Two operators = and & are already overloaded by default in C++. For example: To copy objects of same class, you can directly use = operator. You do not need to create an operator function.
  3. Operator overloading cannot change the precedence and associativity of operators. However, if you want to change the order of evaluation, parenthesis should be used.
  4. The overloaded operators must have one user defined data type.
  5. The overloaded operators follow the syntax rule of original operators, they cannot be over ridden.
  6. we cannot use friend function to overload certain operators(like =,[],(),->).

 Unary operator overloading: 

 Unary operators are overloaded by means of member function take no explicit arguments and the operators overloaded by means of friend function take one argument .

Example:  prefix  operator overloading:- operator symbol is used as prefix as in the example.

#include<iostream>

using namespace std;

class counter

{ unsigned int count;

public: counter() {count=0;}

void showcount()

{cout<<count;}

void operator ++();// operator overloaded function declaration

};

void counter::operator++()

{++coun;}

main()

{

counter c1, c2;

cout<<“c1=”;c1.showcount();

cout<<“c2=”;c2.showcount();

++c1;

++c2;

++c2;

cout<<“after increment;”<<endl;

cout<<“c1=”;c1.showcount();

cout<<“c2=”;c2.showcount();

}

Output:

c1=0c2=0 after increment

c1=1c2=2

Example: post-fix operator overloading:- It requires one argument. When doing this using friend function two arguments are needed one is object and other is ‘int’ as a argument.

#include<iostream>
using namespace std;
class counter

{

int count;

public: counter(){count=0;}

void operator++(int);

void display()

{cout<<“count=”<<count<<endl;}

};

void counter:: operator++(int)

{count++;}

main()

{counter c;

cout<<“initial value of count=”;

c.display();

c++;

c++;

cout<<“after increment count =”;

c.display();

}

Binary operator overloading:

Binary operators overloaded through member function takes only one argument and through friend function takes two arguments. On overloading binary operators through member function left hand operand must be an object of the relevant class to call that function. 

Example: To add two complex numbers

#include<iostream>

using namespace std;

class complex

{ float x, y;

public: complex(){x=0.0;y=0.0;}

complex(float a, float b){x=a; y=b;}

complex operator+(complex);

void display();

};

complex complex::operator +(complex c)

{complex temp;

temp.x=x+c.x;

temp.y=y+c.y;

return(temp);

}

void complex::display()

{ cout<<x<<“+j”<<y<<endl;

}

main()

{

complex c(2.5,7.5), d(3.5,5.5), e;

e=c+d;

cout<<“c=”;c.display();

cout<<“d=”;d.display();

cout<<“e=”;e.display();

}

Output:

c=2.5+j7.5

d=3.5+j5.5

e=6+j13

Leave a Reply

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert
%d bloggers like this: