Define class hierarchy as show in figure.
Store the information of the Book, Tape, CD . Display the information using base pointer. you should not able to make object of base class
Objective
Write a C++ program to achieve Runtime Polymorphism using Base Class Pointers.
Algorithm / Approach
- Create an abstract base
class Mediawith pure virtual functionsinput()anddisplay(). - Create derived classes:
Book,Tape, andCDthat implement these functions. - In
main(), declare pointers of typeMedia*. - Point those base pointers to dynamically created derived objects (e.g.,
Media *m = new Book();). - Call the functions using the arrow operator (
m->input()).
main.cpp
#include<iostream>
using namespace std;
class Media {
public :
string title;
int price;
virtual void input() = 0;
virtual void display() = 0;
};
class Book : public Media {
public:
int page;
void input() {
cout<<"Enter Title of Book: ";
getline(cin,title);
cout<<"Enter Price: ";
cin>>price;
cout<<"Enter No. of Page: ";
cin>>page;
cin.ignore(1,'\n');
}
void display() {
cout<<"Information of Book\n";
cout<<"Title - "<< title<< endl;
cout<<"Price - "<< price<< endl;
cout<<"Pages - "<< page<< endl;
}
};
class Tape:public Media {
public :
int r;
void input() {
cout<<"Enter Title of Tape: ";
getline(cin,title);
cout<<"Enter Price: ";
cin>>price;
cout<<"Enter Run Time in Min: ";
cin>>r;
cin.ignore(1,'\n');
}
void display() {
cout<<"Information of Tape\n";
cout<<"Title - "<< title<< endl;
cout<<"Price - "<< price<< endl;
cout<<"Run Time - "<< r<<" min\n";
}
};
class CD : public Media {
public :
int cap;
void input() {
cout<<"Enter Title of CD: ";
getline(cin,title);
cout<<"Enter Price: ";
cin>>price;
cout<<"Enter Capacity in GB: ";
cin>>cap;
}
void display() {
cout<<"Information of CD\n";
cout<<"Title - "<< title<< endl;
cout<<"Price - "<< price<< endl;
cout<<"CAPACITY- "<< cap<<" GB\n";
}
};
int main() {
Media *m = new Book();
Media *m2 = new Tape();
Media * m3 = new CD;
m->input();
m2->input();
m3->input();
m->display();
m2->display();
m3->display();
return 0;
}
Expected Output
Enter Title of Book: Java Enter Price: 400 Enter No. of Page: 234 Enter Title of Tape: Song Enter Price: 30 Enter Run Time in Min: 120 Enter Title of CD: Panasonic Enter Price: 20 Enter Capacity in GB: 1 Information of Book Title - Java Price - 400 Pages - 234 Information of Tape Title - Song Price - 30 Run Time - 120 min Information of CD Title - Panasonic Price - 20 CAPACITY - 1 GB
Explanation of the Program
- This is the heart of Polymorphism. A pointer of a Base Class type is perfectly allowed to point to an object of ANY of its Derived Classes!
- When you call a
virtualfunction through a base pointer, C++ waits until the program is actually running (Runtime) to check what kind of object the pointer is currently looking at, and dynamically executes the correct child version of the function.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)