Implement the Shape hierarchy designed (which is based on the hierarchy of Fig below). Each TwoDimensionalShape should contain function getArea to calculate the area of the two-dimensional shape. Each ThreeDimensionalShape should have member functions getArea and getVolume to calculate the surface area and volume, respectively, of the three-dimensional shape. Create a program that uses a vector (array) of Shape pointers to objects of each concrete class in the hierarchy. The program should print the object to which each vector (array) element points. Also, in the loop that processes all the shapes in the vector (array), determine whether each shape is a TwoDimensionalShape or a ThreeDimensionalShape. If a shape is a TwoDimensionalShape, display its area. If a shape is a ThreeDimensionalShape, display its area and volume
#include <iostream>
#include <vector>
using namespace std;
const double PI=3.1415926;
class Shape {
public:
virtual void print() = 0;
};
class TwoDimentionalShape : public Shape {
public:
virtual double getArea() = 0;
};
class Square : public TwoDimentionalShape {
public:
Square(double a) : side(a) {}
virtual void print() {
cout << "Square with side " << side;
}
virtual double getArea() {
return side * side;
}
private:
double side;
};
class Circle : public TwoDimentionalShape {
public:
Circle(double r) : radius(r) {}
virtual void print() {
cout << "Circle with radius " << radius;
}
virtual double getArea() {
return PI * radius * radius;
}
private:
double radius;
};
class ThreeDimentionalShape : public Shape {
public:
virtual double getArea() = 0;
virtual double getVolume() = 0;
};
class Cube : public ThreeDimentionalShape {
public:
Cube(double a) : side(a) {}
virtual void print() {
cout << "Cube with side " << side;
}
virtual double getArea() {
return 6 * side * side;
}
virtual double getVolume() {
return side * side * side;
}
private:
double side;
};
class Sphere : public ThreeDimentionalShape {
public:
Sphere(double r) : radius(r) {}
virtual void print() {
cout << "Sphere with radius " << radius;
}
virtual double getArea() {
return 4*PI * radius * radius;
}
virtual double getVolume() {
return 4*PI/3 * radius * radius * radius;
}
private:
double radius;
};
int main() {
vector<Shape*> v;
v.push_back(new Circle(1));
v.push_back(new Square(10));
v.push_back(new Sphere(2));
v.push_back(new Cube(1.1));
v.push_back(new Circle(2.2));
for (int i=0; i<v.size(); i++) {
v[i]->print();
TwoDimentionalShape *shape2d = dynamic_cast<TwoDimentionalShape*>(v[i]);
if (shape2d) {
cout << " has area " << shape2d->getArea() << endl;
}
ThreeDimentionalShape *shape3d = dynamic_cast<ThreeDimentionalShape*>(v[i]);
if (shape3d) {
cout << " has volume " << shape3d->getVolume()
<< " and area " << shape3d->getArea() << endl;
}
}
for (int i=0; i<v.size(); i++) {
delete v[i];
}
}
Comments
Leave a comment