In: Computer Science
Programming Language: C++
Create a base class called Shape which has 2 attributes: X and Y (positions on a Cartesian coordinate system). Since a shape is amorphous, set the class up so that an object of type Shape can not be instantiated.
Create three derived classes of your choice whose base class is Shape. These derived classes should have accessors/mutators for their class specific attributes, as well as methods to compute the area and the perimeter of the shape.
In main(), create a stack of pointers to Shape and push one object of each derived class onto the stack. Then, pop each shape pointer off of the stack and output that shape's area and perimeter, demonstrating polymorphism.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
const double pi = 22.0/7.0;
class Shape
{
public:
string color;
bool filled;
Shape();
Shape(string color,bool filled){
this->color = color;
this->filled =filled;
}
string getColor(){
return this->color;
}
void setColor(string color){
this->color = color;
}
bool isFilled(){
return this->filled;
}
void setFilled(bool filled){
this->filled = filled;
}
string toString(){
return "Color : "+this->color+"
filled : "+((this->filled)?"True ":"False")+"\n";
}
virtual double getArea() = 0;
virtual double getPerimeter() = 0;
};
class Circle:public Shape
{
public:
double radius;
Circle();
Circle(double radius,string color,bool filled) :
Shape(color,filled){
this->radius = radius;
}
double getRadius(){
return this->radius;
}
void setRadius(double radius){
this->radius = radius;
}
double getDiagmeter(){
return this->radius*2;
}
double getArea(){
return this->radius *
this->radius * pi;
}
double getPerimeter(){
return 2*this->radius*pi;
}
};
class Rectangle:public Shape
{
public:
double width;
double height;
Rectangle();
Rectangle(double width,double height, string
color,bool filled) : Shape(color,filled){
this->width = width;
this->height = height;
}
double getWidth(){
return this->width;
}
void setWidth(double width){
this->width = width;
}
double getHeight(){
return this->height;
}
void setHeight(double height){
this->height = height;
}
double getArea(){
return this->width *
this->height;
}
double getPerimeter(){
return 2*(this->width +
this->height);
}
};
class Square:public Shape
{
public:
double side;
Square();
Square(double side, string color,bool filled) :
Shape(color,filled){
this->side = side;
}
double getSide(){
return this->side;
}
void setSide(double side){
this->side = side;
}
double getArea(){
return this->side *
this->side;
}
double getPerimeter(){
return 4*(this->side);
}
};
int main(){
stack<Shape *> shapes;
Shape *a = new Circle(2.3,"blue",true);
Shape *b = new Rectangle(2,5,"black",false);
Shape *c = new Square(5,"red",true);
shapes.push(a);
shapes.push(b);
shapes.push(c);
while(!shapes.empty()){
Shape *shape = shapes.top();
cout<<shape->getArea()<<endl;
cout<<shape->getPerimeter()<<endl;
shapes.pop();
}
}