Question #39188

Create C++ classes for an inheritance hierarchy for shapes as shown in the diagram on next
page. The Shape has a pure virtual function SurfaceArea that needs to be implemented in its
derived classes.
class Shape
{
protected:
string name;
public:
Shape(string n) : name(n) {}
virtual float SurfaceArea() = 0;

You need to add appropriate data members to the derived classes and implement the
SurfaceArea function as Shape2D and Shape3D class. Write a main() to test Square, Circle,
Rectangle, Cylinder, and Pyramid objects.
1

Expert's answer

2014-03-04T10:21:58-0500
#include <iostream>
#include <string>
#include <math.h>
#include <stdlib.h>
using namespace std;
#define pi 3.1415926535897932384626433832795
class Shape
{
protected:
    string name;
public:
    Shape(string n): name(n) {}
    virtual float SurfaceArea() = 0;
};
class Shape2D:public Shape
{
    float par;
public:
    Shape2D(string n, float a):par(a), Shape(n) {};
    float SurfaceArea()
    {
        if(name == "Square")
            return par*par;
        if(name == "Circle")
            return pi*par*par;
        if(name == "Triangle")
            return sqrt(3)*par*par/4;
    }
};
class Shape3D:public Shape
{
    float par1, par2;
public:
    Shape3D(string n, float a, float b):par1(a), par2(b), Shape(n) {};
    float SurfaceArea()
    {
        if(name == "Cylinder")
            return (2*pi*par1*par1) + (2*pi*par1*par2); //par1 - radius, par2 - height
        if(name == "Pyramid") //4-angle pyramid
            return (2*par1*sqrt(par2*par2+par1*par1/4) + par1*par1); //par1 - side, par2 - height
    }
};
int main()
{
    Shape2D Square1("Square", 1);
    cout << "Square, s area: " << Square1.SurfaceArea() << endl;
    Shape2D Circle1("Circle", 1);
    cout << "Circle, s area: " << Circle1.SurfaceArea() << endl;
    Shape2D Triangle1("Triangle", 1);
    cout << "Triangle, s area: " << Triangle1.SurfaceArea() << endl;
    Shape3D Pyramid1("Pyramid", 1, 1);
    cout << "Pyramid,s surface area: " << Pyramid1.SurfaceArea() << endl;
    Shape3D Cylinder1("Cylinder",1,1);
    cout << "Cylinder,s surface area: " << Cylinder1.SurfaceArea() << endl;
    system("PAUSE");
}

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!
LATEST TUTORIALS
APPROVED BY CLIENTS