a1 = a2 + a3;
The above operation is valid, as you know if a1, a2 and a3 are instances of in-built Data Types. But what if those are, say objects of a Class; is the operation valid?
Yes, it is, if you overload the ‘+’ Operator in the class, to which a1, a2 and a3 belong.
Operator overloading is used to give special meaning to the commonly used operators (such as +, -, * etc.) with respect to a class. By overloading operators, we can control or define how an operator should operate on data with respect to a class.
Operators are overloaded in C++ by creating operator functions either as a member or a s a Friend Function of a class. Since creating member operator functions are easier, we’ll be using that method in this article.
As I said operator functions are declared using the following general form:
ret-type operator#(arg-list);
and then defining it as a normal member function.
Here, ret-type is commonly the name of the class itself as the operations would commonly return data (object) of that class type.
# is replaced by any valid operator such as +, -, *, /, ++, -- etc.
Now that you have understood the theory, let’s have a look at an example program:
// Example program to illustrate // operator overloading #include <iostream.h> class myclass { int sub1, sub2; public: // default constructor myclass(){} // main constructor myclass(int x, int y){sub1=x;sub2=y;} // notice the declaration myclass operator +(myclass); void show(){cout<<sub1<<endl<<sub2;} }; // returns data of type myclass myclass myclass::operator +(myclass ob) { myclass temp; // add the data of the object // that generated the call // with the data of the object // passed to it and store in temp temp.sub1=sub1 + ob.sub1; temp.sub2=sub2 + ob.sub2; return temp; } void main() { myclass ob1(10,90); myclass ob2(90,10); // this is valid ob1=ob1+ob2; ob1.show(); }
At this stage many of you might be wondering why the operator function is taking only one argument when it’s operating on two objects (i.e. it’s a binary operator).
To understand this, first have a look at this line of code:
ob1 = ob1 + ob2;
Now assume that ‘operator+’ function is just a regular function which is called as below when the respective operator (‘+’ in this case) is encountered with respect to the objects of its class.
ob1 = ob1.operator+(ob2);
Something like this happens internally when an overloaded operator is encountered. As you can understand from this, when an operator is encountered, the objects to the left generates a call to the operator function to which ob3 is passed, the function does the operation as defined and returns the result as an object which is then assigned to ob1.
Now I think it’s clear why a overloaded binary operator is taking only one argument.
Related Articles: