Operator Overloading and Polymorphism
Operator Overloading and Polymorphism
and Polymorphism
Dr. Miral M. Desai
Department of EC Engineering
FTE, CSPIT, CHARUSAT
Operator Overloading (1)
• 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. It is an idea of giving special
meaning to an existing operator in C++ without changing its original meaning.
• we can overload an operator ‘+’ in a class like String so that we can concatenate two
strings by just using +.
• Here, variables “a” and “b” are of types “int” and “float”, which are built-in data types.
Hence the addition operator ‘+’ can easily add the contents of “a” and “b”. This is
because the addition operator “+” is predefined to add variables of built-in data type
only.
Operator Overloading (2)
• Here, we have 3 variables “a1”, “a2” and “a3” of type “class A”. Here
we are trying to add two objects “a1” and “a2”, which are of user-
defined type i.e. of type “class A” using the “+” operator.
• This is not allowed, because the addition operator “+” is predefined
to operate only on built-in data types.
• But here, “class A” is a user-defined type, so the compiler generates
an error.
• Now, if the user wants to make the operator “+” add two class
objects, the user has to redefine the meaning of the “+” operator
such that it adds two class objects.
• This is done by using the concept of “Operator overloading”.
• So the main idea behind “Operator overloading” is to use C++
operators with class variables or class objects.
• Redefining the meaning of operators really does not change their
original meaning; instead, they have been given additional meaning
along with their existing ones
Syntax of Operator Overloading
• Here:
• returnType is the return type of the function.
• operator is a keyword.
• symbol is the operator we want to overload. Like: +, <, -, ++, etc.
• arguments is the arguments passed to the function.
Operator Overloading in Unary Operator (Prefix)
• Unary operators operate on only one operand.
• The increment operator ++ and decrement operator --
are examples of unary operators.
Operator Overloading in Unary Operator (Postfix)
Operator Overloading with Return Value
Operator Overloading in Binary Operator
Operator Overloading in Binary Operator
Polymorphism
• The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
• Polymorphism is considered one of the important features of Object-Oriented
Programming.
Function Overloading
• When there are multiple functions with the same name but different parameters, then the functions
are said to be overloaded, hence this is known as Function Overloading.
• Functions can be overloaded by changing the number of arguments or/and changing the type of
arguments.