Overloading Binary Operator
In the binary operator overloading function, there should be one argument to be passed. It is the overloading of an operator operating on two operands. Below is the C++ program to show the overloading of the binary operator (+) using a class Distance with two distant objects.
// C++ program to show binary
// operator overloading
#include <iostream>
using namespace std;
class Distance {
public:
int feet, inch;
Distance()
{
this->feet = 0;
this->inch = 0;
}
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading (+) operator to
// perform addition of two distance
// object
// Call by reference
Distance operator+(Distance& d2)
{
// Create an object to return
Distance d3;
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;
// Return the resulting object
return d3;
}
};
// Driver Code
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;
// Use overloaded operator
d3 = d1 + d2;
cout << "\nTotal Feet & Inches: " <<
d3.feet << "'" << d3.inch;
return 0;
}
Output
Total Feet & Inches: 18'11
Explanation:
- Line 27, Distance operator+(Distance &d2): Here return type of function is distance and it uses call by references to pass an argument.
- Line 49, d3 = d1 + d2: Here, d1 calls the operator function of its class object and takes d2 as a parameter, by which the operator function returns the object and the result will reflect in the d3 object.
Pictorial View of working of Binary Operator
In these ways, an operator can be overloaded to perform certain tasks by changing the functionality of operators.
Types of Operator Overloading in C++
C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change the function of some specific operators to do some different tasks.
Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function
Here,
- Return_Type is the value type to be returned to another object.
- operator op is the function where the operator is a keyword.
- op is the operator to be overloaded.
Operator Overloading can be done by using three approaches, i.e.
- Overloading Unary Operator.
- Overloading Binary Operator.