In this post we are going to understand one of the most important and often considered complex topic, Operator Overloading. We will get into the depth of Operator Overloading, we will be learning some handy rules, examples and important questions about Operator Overloading.
Concept :
- If we create two or more members having the same name but having different number of type and different parameter, is known as C++ overloading.
- In C++, we can make operators to work for user defined classes. This is called Operator Overloading.
- For example, we can overload the operator ‘+’ in a class like ‘String’ so that we can concatenate two strings by just using ‘+’ (str1 + str2).
Syntax :
return_type class_name :: operator operator_symbol(args)
{
/* functionalities here */
}
SOME HANDY RULES :
- Existing operators can only be overloaded, but new operators cannot be overloaded.
- The overloaded operator contains at least one operand of the user-defined data type.
- When unary operators (which takes 1 arg) 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 it takes one explicit argument, while when they are overloaded through a friend function it will take two explicit argument.
- Compiler will automatically creates a default assignment operator for every class. This default assignment operator will assign all the members of right side to the left side and works fine most of the cases (this behavior is same as copy constructor).
EXAMPLE :
#include<iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{real = r ; imag = i;}
// This is automatically called when '+' is used with between two Complex objects
Complex operator + (Complex const &obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print()
{ cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
/* Call as : c3 = c1.operator+(c2) */
c3.print();
}
// OUTPUT : 12 + i9
NOTE :
Operator overloading makes a program more readable. Suppose a program is to add two matrices ‘a’ and ‘b’;
instead of using function call of the form —
c = mat_add(a, b);
a more intuitive form will be —
c = a + b;
SOME QUESTIONS :
(1) Which operator can not be overloaded ?
Operators that can’t be overloaded are ‘.’, ‘::’, ‘?’, ‘:’
(2) What is the precendence of overloaded operators ?
The operators will have the same precedence as the intrinsic operations that use the same operators.
There is no way to change operator precedence.
(3) Is it possible to re-define intrinsic operators ?
(Is it possible to create our own operator to add two ints ?)
No. Allowing us to change the behavior of intrinsic operations would make any program virtually unreadable.