Operator Overloading
Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this ability is known
as operator overloading. Operator overloading is a compile-time polymorphism. For example, we can
overload an operator ‘+’ in a class like String so that we can concatenate two strings by just using +.
Other example classes where arithmetic operators may be overloaded are Complex Numbers, Fractional
Numbers, Big integers, etc.
Syntax:
Here,
2. Member and Non-member functions: We can overload operators in two ways:- first is
as a member functions , second is as a non-member functions. When overloading as a
member function, the left operand represents the object on which the function is called
and when overloading as a non-member function, we can specify any type for the left
operand.
3. Number of operands Required: Most operators can be overloaded with one or two
operands. Example- Unary operators like ++ require one operand, while binary operators
like + require two operands.
4. Precedence and associativity: Operator precedence and associativity cannot be changed
when overloading operators. Example- It’s not allowed to change the precedence of (*) or
the associativity of (/).
5. Return type: When we overload operators than we must define the return type of the
overloaded operator function according to our need.
7. Special Syntax: For operators like (), [], or -> we must use a special syntax when
overloading. Example, in order to overload the [] operator and to make objects callable
like functions, we need to define a function named operator().