You are on page 1of 9

Online Lecture 1- EC312 OOP

Polymorphism &&
Introduction to C++ Pointers

Ref: Object Oriented Programming using C++ and JAVA, E. Balaguruswamy, Mc Graw Hill
Education
Polymorphism
• Process of representing one form in multiple
forms
• One form represents original form resides in
base class and multiple forms represents
overridden method which resides in derived
class
• Derived from Greek word, Poly – many,
Morphs - forms
Real life example
• A person at the same time can have different
roles in life – as a father, as employee, as son,
as husband…etc.
• Same person possess different behavior in
different situations
• This is called Polymorphism
Types of Polymorphism
Compile Time Polymorphism
• Also called as Static Binding / Static Linking /
Early Binding
• compiler is aware of the functions with same
name and also which overloaded function is to
be called.
• Implemented using Operator Overloading and
function overloading.
Function overloading Example
#include<iostream>
using namespace std; int main()
class example {
{
example obj;
Public:
void func(int a) obj.func(5);
{ obj.func(‘A’);
cout<<“\n The value of a is”<<a; obj.func(2,3);
}
void func(int a, int b)
Return 0;
{
cout<<“\n The value of a is”<<a; }
cout<<“\n The value of b is”<<b;
}
void func(char c)
{
cout<<“\n The value of c is”<<c;
}
};
Run Time Polymorphism
• Dynamic Binding / Late Binding / Dynamic Linking
• Call to an overridden method is resolved
at runtime rather than at compile-time.
• Implemented using Overriding method/ Virtual
Functions
• C++ Function Overriding -> If derived class
defines same function as defined in its base class
• Overriding function should have same name,
same return type and same argument list.
Function overriding Example
#include<iostream> int main()
using namespace std; {
class base base b;
{ derived d;
Public: b.show_val();
void show_val() d.show_val();
{ }
cout<<“\n Base”;
}
};
class derived: public base
{
Public:
void show_val()
{
cout<<“\n Derived”;
}
};
Virtual Function
• For an overridden function should be bound
dynamically to the function body ->
• base class function is made virtual by using
keyword “Virtual”
• VF is a function which is overridden in the
derived class and compiler carries out late or
dynamic binding for this function

Will be continued…………..tomorrow 7PM

You might also like