Operator Overloading
Operator Overloading
Polymorphism
int main()
{
int n1 = 10, n2 = 20, n2;
String s1 = “Rising”, s2=“Tech”, s3;
n3 = n1 + n2; // addition
s3 = s1 + s2; // concatenation
}
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 6
Overloading Operators
Operators come in three flavours:
Unary (++, --)
Binary (+, -)
Ternary (?:)
You are free to overload most of the built-in operators, but you
cannot create new operators of your own.
Therefore, although you can give your class an increment
operator (++), you cannot create a squared operator.
RetType ClassName::operator#(arg-list)
{
// operations
}
Often, operator functions returns an object of the class they
operate on, but ret-type can be any valid type.
The # is a placeholder. When you create an operator function,
substitute the operator for the #.
RetType ClassName::operator#(arg-list)
{
// operations
}
For example, if you are overloading the + operator, use
operator+
While overloading binary operators using member function,
the arg-list will contain one parameter.
RetType ClassName::operator#()
{
// operations
}
While overloading an unary operator, arg-list will be empty.
RetType operator#(arg-list)
{
// operations
}
While overloading a binary operator using friend function;
argument list must take 2 arguments, one of them must be of
user defined type.
RetType operator#(arg-list)
{
// operations
}
While overloading an unary operator using friend function;
argument list must have 1 argument as reference to the object.