C++ concept of Polymorphism

KiranDelhiPatel 522 views 11 slides Jul 14, 2018
Slide 1
Slide 1 of 11
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11

About This Presentation

Polymorphism means ‘one name, multiple forms’.

Polymorphism is one of the crucial features of OOP.


Slide Content

Polymorphism Submitted by Kiran Patel

What Is Polymorphism Polymorphism means ‘one name, multiple forms’. Polymorphism is one of the crucial features of OOP.

Compile Time Polymorphism:- For every function call compiler binds the call to one function definition at compile time. This decision of binding among several functions is taken by considering formal arguments of the function, their data type and their sequence. There are two type of compile time polymorphism. Function overloading. Operator overloading

Overloading:- Two or more methods with different signatures. Overriding:- Replacing an inherited method with another having the same signature.

Example of Function overloading /* C++ Program to return absolute value of variable types integer and float using function overloading */   #include < iostream > using namespace std;   int absolute( int ); float absolute(float); int main() { int a = -5; float b = 5.5;

cout <<"Absolute value of "<<a<<" = "<<absolute(a)<< endl ; cout <<"Absolute value of "<<b<<" = "<<absolute(b); return 0; }   int absolute( int var ) { if ( var < 0) var = - var ; return var ; }   float absolute(float var ){ if ( var < 0.0) var = - var ; return var ; }   Output:- Absolute value of -5 = 5 Absolute value of 5.5 = 5.5  

Run time Polymorphism C++ allows binding to be delayed till run time. When you have a function with same name, equal number of arguments and same data type in same sequence in base class as well derived class and a function call of form: base_class_type_ptr -> member_function ( args ); will always call base class member function. The keyword virtual on a member function in base class indicates to the compiler to delay the binding till run time. Every class with atleast one virtual function has a vtable that helps in binding at run time.

Run time polymorphism is also known as Dynamic binding and Also known as late binding. In Dynamic binding Calls to overridden methods are resolved at execution time, based on the type of object referenced

Example of run time polymorphism: class Base { public:     virtual void display( int i )     { cout <<"Base::"<< i ; } }; class Derv: public Base { public:     void display( int j)     { cout <<"Derv::"<<j; } }; int main() {     Base * ptr =new Derv;     ptr ->display(10);     return 0; }  Output: Derv::10
Tags