Operator overloading in C++

The overloading concept in C++ is not just applied when writing functions, but to operators as well. These operators include


What does this exactly mean? Well basically it means we can overwrite the function of the symbols shown above so that they do something else. C++ allows us the ability to define a function for each operator symbol in our user defined classes. Like any other function, an overloaded operator has a return type and a parameter list.

<pre>ThreeD operator+(ThreeD ob1, ThreeD ob2)</pre>

Here is an example of operator overloading with ++ prefix

<pre>// Operator overloading example with ++ prefix
class ThreeD
 int x,y,z; // 3D coordinates
 ThreeD() {x = y = z = 0;}
 ThreeD(int i, int j, int k) {x=i, y=j, z=k;}

 void show() {cout<<'\t'<<x<<'\t'<<y<<'\t'<<z<<'\n';}
 friend ThreeD operator+(ThreeD ob1, ThreeD ob2);

ThreeD operator+(ThreeD ob1, ThreeD ob2)
 ThreeD temp;
 temp.x = ob1.x + ob2.x; // These are the integer additions
 temp.y = ob1.y + ob2.y; // and the + retains its original
 temp.z = ob1.z + ob2.z; // meaning relative to them.
 return temp; // Return a new object.

void main()
 ThreeD a(1, 2, 3), b(10, 10, 10), c(0, 0, 0);
 cout << "Original values of a:" ;

 cout << "Original values of b:" ;
 c = a + b;

 cout << "\nValue of c after c=a+b:";

This is just the basis of operator overloading in C++ as there are many further details. The key thing to understand from this is operator overloading allows us to overwrite functions with operator symbols so that they do something else.

Share this post