Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
operator
communitycreator

What is operator overloading in C++?

Saad Akbar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

C++ has the ability to overload operators according to the specific requirements for different user-defined classes. For instance, we may overload a + operator to add two complex numbers or two strings by concatenating them.

Overloaded operators have the keyword operator at the start, followed by the operator symbol that is to be overloaded.

Syntax

Class_name operator+(const Class_name&);

The following code shows the + operator is overloaded to add two Class_name objects:

Code example

#include<iostream>
using namespace std;
class Algebra
{
private:
int x;
int y;
public:
//Constructors
Algebra()
{x=0; y=0;}
Algebra(int r, int i )
{x = r; y = i;}
void display()
{ cout << x << "x + " << y <<"y"<< '\n'; }
friend Algebra operator + (Algebra const &, Algebra const &);
};
Algebra operator + (Algebra const &a1, Algebra const &a2)
{
return Algebra(a1.x + a2.x, a1.y + a2.y);
}
int main()
{
Algebra a1(8, 4);
Algebra a2(7, 9);
Algebra a3 = a1 + a2;
a3.display();
return 0;
}
Program to add two algebraic expressions through operator overloading

Explanation

  • Line 1-18: We declare the class. The default and parameterized constructors are defined to store the values in class variables. The display function is also defined to print the expression.
  • Line 21-28: We declare the operator function as a friend of the class so that the class’s private members can access it. The implementation is shown outside the class, where two Algebra objects are taken in as parameters. Their x and y components are added independently, and the resultant algebraic expression is returned.
  • Line 33-36: We declare two Algebra objects and add them together. The resultant expression is then stored in a new Algebra object displayed using the display() function.

RELATED TAGS

c++
operator
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring