Wed Nov 27 2019
Runtime Polymorphism
C++ Programming1986 views
File Name: runtime-polymorphism.cpp
#include<iostream>
#include<cstring>
#include<iomanip>
using namespace std;
class tutorial {
protected:
char language[30];
float price;
public:
tutorial(char *lng, float prc) {
/* Copy string */
strcpy(language, lng);
price = prc;
}
/* Empty virtual function */
virtual void display() { }
};
class code : public tutorial {
int lines;
public:
code(char *lngue, int ln, float price) : tutorial(lngue, price) {
lines = ln;
}
void display() {
cout << "\n<------------Code------------>\n" << endl;
cout << "Language: " << language << endl;
cout << "Lines of Code: " << lines << endl;
/* 'setprecision(2)' and 'fixed' use to print fixed two decimal point */
cout << "Price: " << setprecision(2) << fixed << price << endl;
}
};
class video : public tutorial {
float runtime;
public:
video(char *lngue, float time, float price) : tutorial(lngue, price) {
runtime = time;
}
void display() {
cout << "\n<------------Video------------>\n" << endl;
cout << "Language: " << language << endl;
cout << "Runtime: " << setprecision(2) << fixed << runtime << endl;
cout << "Price: " << setprecision(2) << fixed << price << endl;
}
};
int main() {
char *langu = new char[30];
float price, time;
int lines;
/* Code tutorial */
cout << "\nEnter code tutorial details" << endl;
cout << "Language: " << endl;
cin >> langu;
cout << "Lines of code:" << endl;
cin >> lines;
cout << "Price:" << endl;
cin >> price;
code cd(langu, lines, price);
/* Video tutorial */
cout << "\nEnter video tutorial details" << endl;
cout << "Language: " << endl;
cin >> langu;
cout << "Runtime:" << endl;
cin >> time;
cout << "Price:" << endl;
cin >> price;
video vd(langu, time, price);
/* Object pointer */
tutorial *list[2];
list[0] = &cd;
list[1] = &vd;
cout << "\nTutorial Details" << endl;
/* Display code tutorial details using member access operator */
list[0]->display();
/* Display video tutorial details using member access operator */
list[1]->display();
return 0;
}
/* Output */
Enter code tutorial details
Language:
Java
Lines of code:
200
Price:
20.50
Enter video tutorial details
Language:
C++
Runtime:
5.3
Price:
30.5
Tutorial Details
<------------Code------------>
Language: Java
Lines of Code: 200
Price: 20.50
<------------Video------------>
Language: C++
Runtime: 5.30
Price: 30.50
Reference:
Author:Geekboots