C++ Operator Overloading
In this tutorial, we will learn about Operator Overloading, different approaches, Rules for Operator Overloading and how to overload Operator with the help of examples.
Overloading
If we Create two or more members that have the same name but are different in number or type of parameter is known as "Overloading" .
In C++, we can overload:
- Methods
- Constructors
- Indexed Properties
We can overload these members because they have parameters only.
Types of Overloading
There are two types of Overloading as follows:
- Function Overloading.
- Operator Overloading.
In Earlier Tutorials, we already discuss the Function Overloading, In this tutorial we will discuss Operator Overloading.
Operator Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide special meaning to the user-defined data type. Operator overloading is used to overload or redefine most of the operators available in C++. It is used to perform the operation on the user-defined data type.
Using operator overloading in C++, you can specify more than one meaning for an operator in one scope.
For example :- '+' operator can be overloaded to perform addition on various data types, like for Integer, String(concatenation) etc.
Other example :- classes where arithmetic operators may be overloaded are Complex Number, Fractional Number, Big Integer, etc.
The advantage of operator overloading is that it can perform different operations on the same operand.
For Example:-
Suppose we have created three objects a1, a2 and sum from a class named Complex
that represents complex numbers.
Since operator overloading allows us to change how operators work, we can redefine how the +
operator works and use it to add the complex numbers of a1 and a2 by writing the following code:
sum = a1 + a2;
instead of something like
sum = a1.addNum(a2);
This makes our code intuitive and easy to understand.
Note: We cannot use operator overloading for fundamental data types like int
, float
, char
and so on.
Syntax for Operator Overloading in C++
To overload an operator, we use a special operator
function.
class className {
... .. ...
public
return_type operator symbol (argument(s)) {
... .. ...
}
... .. ...
};
Here, is an explanation for the above syntax:
return_type
is the return type of the function.- Next, we mention the operator keyword.
symbol
is the operator we want to overload. Like:+
,<
,-
,++
, etc.argument(s)
can be passed to the operator function in the same way as function.
What is the difference between operator functions and normal functions?
Operator functions are same as normal functions. The only differences are, name of an operator function is always operator keyword followed by symbol of operator and operator functions are called when the corresponding operator is used.
Moving on with this article on Operator Overloading in C++.
Types of Overloading approaches
Operator Overloading can be done by using three approaches, they are
- Overloading unary operator.
- Overloading binary operator.
- Overloading binary operator using a friend function.
Operator Overloading in Unary Operators
Unary operators operate on only one operand. The increment operator ++
and decrement operator --
are examples of unary operators.
For Example:-
Example 1: C++ Program to Overload the Unary Operator (++)
#include <iostream>
using namespace std;
class Count {
private:
int num;
public:
// Constructor to initialize count to 2
Count() : value(2) {}
void operator ++ () {
Count num = num + 2;
}
void display() {
cout << "The Count: " << num << endl;
}
};
int main() {
Count c;
// Call the "void operator ++ ()" function
++c;
c.display();
return 0;
}
Output
The Count: 4
Example 2: C++ Operator Overloading using Unary Operator
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
// Constructor to initialize count to 4
Count() : value(4) {}
// Overload ++ when used as prefix
Count operator ++ () {
Count test;
// Here, value is the value attribute of the calling object
test.value = ++value;
return temp;
}
// Overload ++ when used as postfix
Count operator ++ (int) {
Count test;
// Here, value is the value attribute of the calling object
test.value = ++value;
return test;
}
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1, result;
// Call the "Count operator ++ ()" function
result = ++count1;
result.display();
// Call the "Count operator ++ (int)" function
result = count1++;
result.display();
return 0;
}
Output
Count: 5 Count: 6
Here, we have used the following code for prefix operator overloading:
// Overload ++ when used as prefix
Count operator ++ () {
Count test;
// Here, value is the value attribute of the calling object
test.value = ++value;
return test;
}
The code for the postfix operator overloading is the same as well. Notice that we have created an object test and returned its value to the operator function.
Also notice the code
test.value = ++value;
The variable value belongs to the count1 object in main()
because count1 is calling the function, while test.value belongs to the test object.
Operator Overloading in Binary Operators
Binary operators work on two operands. For example,
result = num + 9;
Here, +
is a binary operator that works on the operands num and 9
.
When we overload the binary operator for user-defined types by using the code:
obj3 = obj1 + obj2;
The operator function is called using the obj1 object and obj2 is passed as an argument to the function.
Example 3: C++ Binary Operator Overloading
#include <iostream>
using namespace std;
class A {
int n;
public:
A(){}
A (int s) {
n = s;
}
void operator + (A);
void display ();
};
void :: operator+ (A a) {
int m = n + a.n;
cout << "The Result of addition of two objects: " << m << endl;
}
int main() {
A a1(5);
A a2(4);
a1 + a2;
return 0;
}
Output
The Result of addition of two objects: 6
Example 4: C++ Program to overload the binary operator and adds two complex numbers
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imagine;
public:
// Constructor to initialize real and imagine to 0
Complex() : real(0), imagine(0) {}
void input() {
cout << "Enter real and imaginary Number respectively: ";
cin >> real;
cin >> imagine;
}
// Overload the + operator
Complex operator + (const Complex& obj) {
Complex test;
test.real = real + obj.real;
test.imagine = imagine + obj.imagine;
return test;
}
void output() {
if (imagine < 0)
cout << "Output Complex number: " << real << imagine << "i";
else
cout << "Output Complex number: " << real << "+" << imagine << "i";
}
};
int main() {
Complex complex1, complex2, result;
cout << "Enter first complex number:\n";
complex1.input();
cout << "Enter second complex number:\n";
complex2.input();
// complex1 calls the operator function
// complex2 is passed as an argument to the function
result = complex1 + complex2;
result.output();
return 0;
}
Output
Enter first complex number: Enter real and imaginary parts respectively: 6 3 Enter second complex number: Enter real and imaginary parts respectively: 5 4 Output Complex number: 11+7i
In this program, the operator function is:
Complex operator + (const Complex& obj) {
// code
}
Instead of this, we also could have written this function like:
Complex operator + (Complex obj) {
// code
}
However,
- using
&
makes our code efficient by referencing the complex2 object instead of making a duplicate object inside the operator function. - using
const
is considered a good practice because it prevents the operator function from modifying complex2.
Things to Remember in C++ Operator Overloading
- With operator overloading, you can redefine the way an operator works only for the user-defined types (objects, structures). You cannot use it for built-in types (float, char, int, etc.).
- Two operators
=
and&
are already overloaded by default in C++. For example, to copy objects of the same class, we can directly use the=
operator. We do not need to create an operator function. - Operator overloading cannot change the precedence and associativity of operators. However, if we want to change the order of evaluation, parentheses should be used.
- There are 5 operators that cannot be overloaded in C++. They are:
::
scope resolution operator?:
ternary operator.
member selector- sizeof Operator
*
member pointer selector
Rules for Operator Overloading
Here are the rules for Operator Overloading:
- For it to work, at least one operand must be a user-defined class object.
- You can only overload existing operators. You can't overload new operators.
- Some operators cannot be overloaded using a friend function. However, such operators can be overloaded using member function.
Visit these pages to learn more on:
- How to overload increment operator in right way?
- How to overload binary operator - to subtract complex numbers?
Next Tutorial
We hope that this tutorial helped you develop better understanding of the concept of Operator Overloading in C++.
Keep Learning : )
In the next tutorial, you'll learn about C++ Friend Function
.