How to Overload the (+) Plus Operator in C++?
Last Updated :
14 Feb, 2024
In C++, operator overloading is a feature of the OOPs concept that allows you to redefine the behavior for different operators when they are used with objects of user-defined classes. The plus operator (+) is a binary operator generally used for addition. In this article, we will learn how to overload the (+) plus operator in C++ for a user-defined class.
Overloading the Plus(+) Operator in C++
To overload the plus operator, we have to create an operator+ function inside our class and define its behavior inside this function’s body. The following syntax shows how to do it:
myClass operator+ (const myClass& obj) const {
// new behaviour
}
C++ Program to Overload the Plus(+) Operator for a Class
C++
#include <iostream>
using namespace std;
class MyClass {
private :
int value;
public :
MyClass(): value(0){}
MyClass( int val): value(val){}
MyClass operator+( const MyClass& other) const
{
MyClass result;
result.value = this ->value + other.value;
return result;
}
int getValue() const { return value; }
};
int main()
{
MyClass obj1(5);
MyClass obj2(10);
MyClass result = obj1 + obj2;
cout << "Result: " << result.getValue() << endl;
return 0;
}
|
To know more about operator overloading, refer to the article – Operator Overloading in C++
Share your thoughts in the comments
Please Login to comment...