Operator Overloading
⚫ Operator overloading is a compile-time polymorphism
⚫ The process in which the c++ operator is redefined for user-defined data types (objects).
⚫ Operator overloading is used to overload or redefines most of the operators available in C++.
⚫ Unary operators (--,++)
⚫ Binary operators
⚫ Arithmetic(+,-,*,/)
⚫ Relational operators (>,<,==,>=,<=)
Explanation
⚫ Normally C++ operators are used for builtin data types like int, float etc
int a,b; a+b (where a and b are int types)
Now
A obj1,obj2; obj1 + obj2 (where both are user-defined types i.e objects)
Operators that cannot be overloaded
⚫ cope operator (::)
⚫ Sizeof
⚫ member selector(.)
⚫ member pointer selector(*)
⚫ ternary operator(?:)
Operator Function
⚫ Special operator function is used for operator overloading
Syntax
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Muhammad Farooq GPGC Swabi