In this C++ tutorial, you will learn about Operator Overloading, how to use Operator Overloading in custom classes to overload a builtin operator and specify your own custom code of operation, with examples.
C++ Operator Overloading in C++
Operator Overloading in C++ is the process of defining a custom logic for an operator to work for user defined classes.
We are already familiar with Operator Overloading, but are not conscious about it. For example, we use +
operator to concatenate two strings. Here, +
operator is overloaded with a definition to concatenate strings when +
is used with two string type objects.
Another example would be complex numbers. When we use +
operator to add two complex numbers, only the respective real and complex parts are added.
Syntax
The syntax to overload operator +
for class A, where + operator returns nothing, is
class A { public: void operator + (A const &a) { // logic } };
The syntax to overload operator +
for class A, where + operator returns an object of type A, is
class A { public: A operator + (A const &a) { A result; // logic return result; } };
The definition for Operator Overloading starts with return type, followed by operator
keyword, then the operator symbol, then the right operand. The logic is enclosed in flower braces just like a member function.
Examples
1. Overload single operator
In the following example, we define a class A. For this class, we overload operator +
for objects of type A using Operator Overloading.
C++ Program
#include <iostream> using namespace std; class A { public: int x; A(int _x = 0) { x = _x; } A operator + (A const &a) { A result; result.x = x + a.x; return result; } }; int main() { A a1(4); A a2(5); A result = a1 + a2; cout << "Result : " << result.x << endl; }
Output
Result : 9 Program ended with exit code: 0
2. Overload Multiple Operators
In the following example, we define a class Log for logarithmic objects. For this class, we overload operator +
and -
.
C++ Program
#include <iostream> using namespace std; class Log { public: double x; Log(int _x = 0) { x = _x; } Log operator + (Log const &a) { Log result; result.x = x * a.x; return result; } Log operator - (Log const &a) { Log result; result.x = x / a.x; return result; } }; int main() { Log a1(4); Log a2(5); Log logAdd = a1 + a2; cout << "log 4 + log 5 = log " << logAdd.x << endl; Log logSub = a1 - a2; cout << "log 4 - log 5 = log " << logSub.x << endl; }
Output
log 4 + log 5 = log 20 log 4 - log 5 = log 0.8 Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned what Operator Overloading is, and how to use Operator Overloading to define custom logic for operations on user defined class objects, with the help of examples.