Operator Overloading
We stated earlier that one of the aims of C++ is to create user-de ned data types such as
class, that behave very similar to the built-in types.
This means that we should be able to perform operations on objects much the same way
as on an ordinary variable.
In C++, we can change the way operators work for user-de ned types like objects and
structures. This is known as operator overloading. For example,
Syntax:
//outside the class
return type classname :: operator op(all the arguments){
//Function body
}
//inside the class
return type operator op(all the arguments){
//Function body
}
fi
fi
Overloading unary operators
- In unary operator function, no arguments should be passed. It works only with one
class object. It is the overloading of an operator operating on a single operand.
Overloading binary operators
- In binary operator overloading function, there should be one argument to be passed. It
is overloading of an operator operating on two operands.
Although the semantics of an operator can be extended, we cannot change its syntax,
the grammatical rules that govern its use such as the number of operands, precedence
and associativity. For example, the multiplication operator will enjoy higher precedence
than the addition operator.
Remember, when an operator is overloaded, its original meaning is not lost. For instance,
the operator +, which has been overloaded to add two fractions, can still be used to add
two integers.
Operators that can’t be overloaded
- We can overload (give additional meaning to) all the C++ operators except the
following:
• Class member access operators (. , .*)
• Scope resolution operator (::)
• Size operator (sizeof)
• Conditional operator (? :)