Answer to Question #285626 in C++ for Asad

Question #285626

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

1
Expert's answer
2022-01-07T13:49:30-0500
#include <iostream>
#include <string>
#include <vector>
#include <math.h>


using namespace std;




class Shape{
public:
	Shape(){}
	
	virtual float getArea(){return 0;}
};




class TwoDimensionalShape :public Shape{
protected:
	float w;
	float h;
public:
	TwoDimensionalShape (){}


	TwoDimensionalShape (float w,float h):Shape(){
		this->w=w;
		this->h=h;
	}


	float getArea(){
		return this->w*this->h;
	}


};


class ThreeDimensionalShape:public TwoDimensionalShape{
private:
	float b;
public:
	ThreeDimensionalShape (float w,float h,float b):TwoDimensionalShape(w,h){
		this->b=h;
	}
	float getArea(){
		return 2*((this->w*this->h)+(this->w*this->b)+(this->h*this->b));
	}
	float getVolume(){
		return this->w*this->h*this->b;
	}
};


int main(){
	vector<Shape*> shapes;
	shapes.push_back(new TwoDimensionalShape(4,5));
	shapes.push_back(new ThreeDimensionalShape(4,5,5));
	shapes.push_back(new TwoDimensionalShape(1,2));
	shapes.push_back(new ThreeDimensionalShape(5,4,2));
	for(int i=0;i<shapes.size();i++){
		TwoDimensionalShape *twoDimensionalShape=dynamic_cast<TwoDimensionalShape*>(shapes[i]);
		ThreeDimensionalShape *threeDimensionalShape = dynamic_cast<ThreeDimensionalShape*>(shapes[i]);
		if(twoDimensionalShape!=NULL){
			cout<<"TwoDimensionalShape\n";
			cout<<"Area: "<<twoDimensionalShape->getArea()<<"\n";
		}
		if(threeDimensionalShape!=NULL)
		{
			cout<<"ThreeDimensionalShape\n";
			
			cout<<"Area: "<<threeDimensionalShape->getArea()<<"\n";
			cout<<"Volume: "<<threeDimensionalShape->getVolume()<<"\n";
		}
	}




	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment