Operator Overloading gives special meaning to the Operator in c++.
A normal c++ Operator acts in a special way to a newly defined datatype.
The advantage of Operator overloading is to perform different operations on the same operand.
The syntax to declare Operator Overloading is :
return_type operator op (argument_list) { // body of the function. }
Return type is the type of value returned by the function.
operator is a Keyword.
op is an operator symbol that you want to overload.
Here’s an example of an Operator Overloading.
void operator + () { // body of the function. }
Some operators are not used for overload :
- ( . and .* ) class member access operator
- ( :: ) scope resolution operator
- ( sizeof ) sizeof operator
- ( ?: ) conditional operator
Also read this :- what is class and object in c++
Rules for Operator Overloading
Existing operators can only be overloaded, but the new operators cannot be overloaded.
The overloaded operator contains at least one operand of the user-defined data type.
We cannot use the friend function to overload certain operators. However, the member function can be used to overload those operators.
When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.
Example of the unary operator ‘-‘ in Operator overloading C++.
#include <iostream> using namespace std; class xyz {   int a, b, c;   public:   void getdata(int p, int q, int r)   {    a = p;    b = q;    c = r;   }   void operator - ()   {    a = -a;    b = -b;    c = -c;   }   void putdata()   {    cout<< a << ", " << b << ", " << c << endl;   } }; int main() {   xyz x1;   x1.getdata(10, 15, 20);   cout<<" X1 = ";   x1.putdata();   -x1; // calling statement   cout<<" X1 = ";   x1.putdata();   return 0; }
output
X1 = 10, 15, 20 X1 = -10, -15, -20
Example of binary operator ‘+’ in Operator overloading C++
#include<iostream> using namespace std; class complex { public: Â Â float x,y; Â Â complex(){}; Â Â complex(float real, float imag){ Â Â Â x = real; y= imag; Â Â } Â Â complex operator+(complex); Â Â void display(void); }; complex complex :: operator+(complex c) { Â Â complex temp; Â Â temp.x = x + c.x; Â Â temp.y = y + c.y; Â Â return(temp); } void complex :: display(void) { Â Â cout<< x <<" + "<< y << "n"; } main(){ Â Â complex c1,c2,c3; Â Â c1 = complex(2.5, 3.5); Â Â c2 = complex(1.6, 2.7); Â Â c3 = c1 + c2; Â Â cout<< "c1 = "; Â Â c1.display(); Â Â cout<< "c2 = "; Â Â c2.display(); Â Â cout<< "c3 = "; Â Â c3.display(); Â Â return(0); }
output
c1 = 2.5 + 3.5 c2 = 1.6 + 2.7 c3 = 4.1 + 6.2