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