Unit 4 Operator Overloading
Unit 4 Operator Overloading
Operator Overloading
Operator Overloading
Method of making operators to work for user defined
data types
It is also a type of polymorphism in which an operator
is overloaded to give user defined meaning to it
For example, ‘+’ operator can be used for addition for
number data types and concatenation for string
We can overload all the C++ operators except
the following:
Class member access operator ( . , .*)
Scope resolution operator (::)
Size operator (sizeof)
Conditional operator ( ? : )
Terniary operator (?:)
int a;
float b,sum;
sum = a + b;
Here a is int and b is float which are built in data types. Hence ‘+’ operator can be used to add
those “a” and “b”. This is because ‘+’ is predefined to add variables of built in data type.
class Student {
};
int main()
}
Eg :
}
Operator is a keyword
Friend function will have only one argument for unary operation and two for binary
operators
Unary Operator Overloading
If overloading takes place on a single operand
using operators like increament(++),
decreament(--), unary minus(-), logical not(!),
etc. is called unary operator overloading
Normally this operator appear as prefix
Example of unary
Operator
Overloading
Using member
function
Example of unary
Operator
Overloading
Using friend
function
Binary Operator Overloading
If overloading takes place on two operands
using binary operators then it is called binary
operator overloading.
The operator overloading mechanism is same
as in unary operator overloading
Example of Binary
Operator
Overloading
Using Member
function
Example of Binary
Operator
Overloading
Using friend
function
Example of Insertion
Operator
Overloading
Output :