Binary Operator Overloading in C++

Binary operator overloading

  • Operator overloading is a compile polymorphic technique where a single operator can perform multiple functionalities
  • As a result, the operator that is overloaded is capable to provide special meaning to the user-defined data types as well.

We can overload binary operators like +,*/, – etc to directly manipulate the object of a class

Syntax:

return_type::operator binary_operator_symbol(parameters)
{
// function definition
}

Here  operator is a keyword and binary operator symbol is the operator to be overloaded

Read more on Operator Overloading in C++ here

Binary Operator Overloading

Steps to perform binary operator overloading

  • Create the class and define its variables and member functions
  • Define the function get_data() to read two numbers
  • Define the function operator +() to add two complex numbers
  • Define the function operator -() to subtract two complex numbers
  • Define the display() function
  • Create the object for the class b1,b2 and result call the function get_data() using these objects
  • Calculate the value for the object result by calling the function operator +()  and operator – () and return the values

C++ program to add and subtract two complex numbers using binary operator overloading

class complex 
{
int a, b;
public:

void get_data()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
}

complex operator+(complex ob)// overaloded operator function +
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}

complex operator-(complex ob)// overaloded operator function -

{
complex t;
t.a = a - ob.a;
t.b = b - ob.b;
return (t);
}

void display()

{
cout << a << "+" << b << "i" << "\n";
}
};

main()
{

complex obj1, obj2, result, result1;

obj1.get_data();
obj2.get_data();

result = obj1 + obj2;
result1 = obj1 - obj2;

cout << "Input Values:\n";
obj1.display();
obj2.display();

cout << "Result:";
result.display();
result1.display();

}

Output

Enter the value of Complex Numbers a, b
3 2
Enter the value of Complex Numbers a, b
2 2
Input Values
3 + 2i
2 + 2i
Result
5 + 4i
1 + 0i