24 Sept 2019

  • September 24, 2019
  • Amitraj

2.) Runtime Polymorphism (Dynamic Binding):-

 Sometimes linking of function call to function definition is not known until program execution.  then,this type of polymorphism is known as runtime polymorphism  or late binding or dynamic   binding.
 * C++ supports a mechanism known as virtual function to achieve run time polymorphism.
 * Dynamic binding is one of the powerful feature of c++.


 Run time Polymorphism Example:


 // C++ program to demonstrate run time polymorphism.

 #include<iostream>
#include<cstring>
using namespace std;
class media
{
protected:
char title[50];
float price;
public:
media(char *s,float a)
{
strcpy(title,s);
price=a;
}
virtual void display()=0;

};
class book: public media
{
int pages;
public:
book(char *s,float a,int p): media(s,a)
{
pages=p;
}
void display();
};
class tape: public media
{
float time;
public:
  tape(char *s,float a,float t): media(s,a)
  {
  time=t;
 }
 void display();
};
void book::display()
{
cout<<"\ntitle:"<<title;
cout<<"\npages:"<<pages;
cout<<"\nprice:"<<price;
}
void tape::display()
{
cout<<"\ntitle:"<<title;
cout<<"\nplay time:"<<time<<"mins";
cout<<"\nprice:"<<price;
}

int main()
{
char *title=new char[30];
float price,time;
int pages;
cout<<"Enter book details:\n";
cout<<"title:";
cin>>title;
cout<<"price:";
cin>>price;
cout<<"pages:";
cin>>pages;
book book1(title,price,pages);
cout<<"\nEnter tape details:\n";
cout<<"title:";
cin>>title;
cout<<"price:";
cin>>price;
cout<<"play time(mins):";
cin>>time;
tape tape1(title,price,time);
media *list[2];
list[0]=&book1;
list[1]=&tape1;
cout<<"media details:";
cout<<"\n....Book....";
list[0]->display();
cout<<"\n ....Tape....";
list[1]->display();
return 0;
}

INPUT/OUTPUT:

Enter book details:
title:c_lang
price:200
pages:400

Enter tape details:
title:c_Audio
price:100
play time(mins):80

media details:
....Book....
title:c_lang
pages:400
price:200
 ....Tape....
title:c_Audio
play time:80mins
price:100

http://codevidyalay.blogspot.com



Translate

Popular Posts