• Consider a class Shape that contains: A data member named as Shape Name of string type. A data member named as area of type int. A member function displayarea() • Derive two classes named Circle and polygon from the class Shape that contain: A parameterized constructor to initialize data members that they inherit from the class Shape. In the main(), create instances of Shape Circle and Polygon classes. Invoke displayarea() with shape object while passing references of Circle and Polygon instances.
#include<iostream>
#include<string>
using namespace std;
//class shape
class Shape
{
private:
string name;
int area;
public:
//constructor to assign initial values Name and area
Shape(string name,int area)
{
this->name=name;
this->area=area;
}
void displayarea()
{
cout<<"The shape "<<this->name<<" has area: "<< this->area<<"\n";
}
};
//class Circle inheriting class Shape
class Circle: public Shape
{
public:
Circle(string name,int area):Shape(name,area){}
};
//class Polygon inheriting class Shape
class Polygon: public Shape
{
public:
Polygon(string name,int area):Shape(name,area){}
};
void main()
{
Shape *s;
Circle c("Circle",50);
s=&c;
s->displayarea();
Polygon p("Polygon",20);
s=&p;
s->displayarea();
int k;
cin>>k;
}
Comments
Leave a comment