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++ program to demonstrate operator overloading of plus // operator #include <iostream> using namespace std;
// Class definition class MyClass {
private :
int value;
public :
// Constructors
MyClass(): value(0){}
MyClass( int val): value(val){}
// Overloaded operator +
MyClass operator+( const MyClass& other) const
{
MyClass result;
result.value = this ->value + other.value;
return result;
}
// Getter method
int getValue() const { return value; }
}; int main()
{ // Create objects
MyClass obj1(5);
MyClass obj2(10);
// Use overloaded operator +
MyClass result = obj1 + obj2;
// Output result
cout << "Result: " << result.getValue() << endl;
return 0;
} |
Result: 15
To know more about operator overloading, refer to the article – Operator Overloading in C++