Polymorphism: Pointers and Polymorphism in C++
Polymorphism: Pointers and Polymorphism in C++
POLYMORPHISM
T Y P E S O F P O LY M O R P H I S M
What Is Polymorphism?
• Polymorphism Is The Combination Of Two Greek Words,
Poly Means : Many
Morphism Means :Forms
• Its stands for “same name multiple forms”.
• It means more than one function with same name ,with different working.
• We can define multiple things, with same name in a program for different purpose.
EXAMPLE
int main()
{
triangle t;
rectangle r;
t.draw (a, b, c);
r.draw (e, f);
}
Function draw() shows the property of Polymorphism it will behave differently with object “t” and
object
“r”.
Real Life Example Of Polymorphism
• So The Same Person Posses Different Behavior In Different Situations. This Is Called
Polymorphism.
Advantages:
1. It helps programmers reuse the code and classes once written.
2. Single variable name can be used to store variables of multiple data types.
TYPES OF POLYMORPHISM
1. COMPILE TIME OR STATIC POLYMORPHISM(STATIC)
• Those Operations That Take Place During The Compile Time Are Called Static Or Compile Time
Polymorphism.
1. Function Overloading:
When There Are Multiple Functions With Same Name But Different Parameters Then These Functions Are
Said To Be Overloaded. Functions Can Be Overloaded By Change In Number Of Arguments Or/And Change
In Type Of Arguments.
2. Operator Overloading:
C++ Also Provide Option To Overload Operators. For Example, We Can Make The Operator (‘+’) For
String Class To Concatenate Two Strings. We Know That This Is The Addition Operator Whose Task Is To
Add Two Operands. So A Single Operator ‘+’ When Placed Between Integer Operands , Adds Them And
When Placed Between String Operands, Concatenates Them.
2. RUN TIME POLYMORPHISM (DYNAMIC)) :
• Runtime Polymorphism Is Also Known As Dynamic Polymorphism Or Late Binding. In
Runtime Polymorphism, The Function Call Is Resolved At Run Time.
A Virtual Function Is Another Way Of Implementing Run-time Polymorphism In C++. It Is A Special Function
Defined In A Base Class And Redefined In The Derived Class. To Declare A Virtual Function, You Should Use
The Virtual Keyword. The Keyword Should Precede The Declaration Of The Function In The Base Class.
keyword ex: ->
Difference Between Static And Dynamic Polymorphism