Consider a class Computer having Two fields (i.e. companyName, price) and A single
function named show()
A class named Desktop inherits Computer class and adds fields representing color,
monitor size, and processor type and Override function named show() to display values
of its all attributes
A class named Laptop inherits Computer class and adds fields representing color, size,
weight, and processor type and Override function named show() to display values of its
all attributes
In Main() instantiate objects of derived classes to access respective show() functions to
see the polymorphic behavior.
#include <iostream>
#include <string>
using namespace std;
class Computer
{
string companyName;
double price;
public:
Computer(string _companyName, double _price)
:companyName(_companyName), price(_price){}
Computer(){}
void show()
{
cout << "\nCompany name is " << companyName
<< "\nPrice is "<<price;
}
};
class Desktop: public Computer
{
string color;
float mon_size;
float weight;
string proc_type;
public:
Desktop(string _companyName,double _price,string _color, float _mon_size,
float _weight, string _proc_type ):Computer(_companyName, _price),
color(_color), mon_size(_mon_size), weight(_weight), proc_type(_proc_type){}
void show()
{
cout << "\nColor is " << color
<< "\nMonitor size is " << mon_size
<< "\nWeight is " << weight
<< "\nProccessor type is " << proc_type;
}
};
class Laptop : public Computer
{
string color;
float siz;
float weight;
string proc_type;
public:
Laptop(string _companyName, double _price, string _color, float _siz, float _weight, string _proc_type)
:Computer(_companyName, _price), color(_color), siz(_siz), weight(_weight), proc_type(_proc_type) {}
void show()
{
cout << "\nColor is " << color
<< "\nSize is " << siz
<< "\nWeight is " << weight
<< "\nProccessor type is " << proc_type;
}
};
int main()
{
Computer *c;
Desktop d("IBM", 3000, "Red", 25, 3.2, "x64");
cout << "\nDesktop data:";
d.show();
c = &d;
cout << "\nComputer data:";
c->show();
Laptop l("HP", 2500, "Blue", 24, 2.8, "x86");
cout << "\nDesktop data:";
d.show();
c = &l;
cout << "\nComputer data:";
c->show();
}
Comments
Leave a comment