Operator Overloading
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 Friend Function of a class
Code:
<return-type> operator <symbol>(<arguments>);
<return-type> is commonly the name of the class itself as the operations would commonly return data (object) of that class type.
<symbol> is replaced by any valid operator such as +, -, *, /, ++, -- etc.
Sample Overloading + Operator
Code:
#include <iostream.h>
class myclass
{
int sub1, sub2;
public:
// default constructor
myclass(){}
// oervloaded 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:
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.
Code:
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.
Operators that can't be overloaded
sizeof
Object size information
typeid
Object type information
::
Used to resolve the scope of variable or function of a class
? :
Ternary Operator (conditional operator)
. (dot)
Dereferencing Operator.
.*
Member selection with pointer to member
Hi!
This is the great information about operator overloading in C++. I have some problem with this operator overloading But I hope my this problem will be solved by this information provided by you. Thank you so much for this superb sharing!