Operator Overloading
A+b=ab // String Concatenation Operator Syntax: return_type operator op (argslist) { function body; } The Mechanism of providing such an additional meaning to an operator is called operator overloading Eg: 2+3=5 // addition A+b=ab // String Concatenation To pass the value Class Name Symbol (+, -)
Need for Operator Overloading To make the user defined data type as natural as fundamental data type. Here fundamental data type refers int, float, double. User defined data types must be associated with appropriate set of operator The user can understand the operator notation more easily It allows the programmer to redefine the meaning of operator when they operate on class objects. It is used by the programmer to make a program clearer More readable and array to understand User don’t need to remember the names of functions
Overloading Unary operator Examples: An Operator which operates on single variable is called unary operator A unary operator is a operator that operates on single operand (varibale or numbers) Eg: -a; Unary operator have precedence over binary operator Syntax: Classname operator - () Unary Operator Description - Unary minus operator + Unary Plus operator * Indirection Operator ++ Incremental - - Decremental Unary minus operator No arguments
Program for Overloading Unary Operator class sample { public: int a,b; void get() cout<<"Enter values of a & b:"; cin>>a>>b; } sample operator -() // declaring overloading unary operator a=-a; b=-b; void display() cout<<"Unary values for a & b:"<<a<<b; }}; void main() sample g; clrscr(); g.get(); -g; g.display; getch(); Output: Enter values of a & b: 4 8 Unary values for a & b: -4 -8