Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

With the given C++ code, what is the best way to utilize the 'calculatePerimeter()' and 'calculateArea()' functions in the inheriting class to work with multiple

With the given C++ code, what is the best way to utilize the 'calculatePerimeter()' and 'calculateArea()' functions in the inheriting class to work with multiple different polygons? I need them to work for polygon 'triangle' all the way to the polygon 'octagon', but am not sure how to implement the functions to work with the different shapes without making more inheriting classes. Here is what I have so far:

class Shape {

private:

string color;

string type;

public:

Shape(string c){

setColor(c);

}

void setColor(string s){

color = s;

}

virtual string getColor(){

return color;

}

void setType(int t){

if (t < 3)

cout << "No Shape / Error" << endl;

if (t == 3)

type = "triangle";

if (t == 4)

type = "square";

if (t == 5)

type = "pentagon";

if (t == 6)

type = "hexagon";

if (t == 7)

type = "heptagon";

if (t == 8)

type = "octogon";

}

string getType(){

return type;

}

virtual double calculatePerimeter(double n)=0;

virtual double calculateArea()=0;

};

// Inheriting Class *******************************

class Polygon : public Shape {

private:

int sides;

double sideLength;

public:

Polygon(string s, int n) : Shape(s){

setColor(s);

setType(n);

}

//Not sure how to implement the two bottom functions below to work with multiple polygons from triangle all the way through octagon

double calculatePerimeter(double n){return 0;};

double calculateArea(){return 0;}

};

int main(){

vector polygonList; // list of types of polygons

polygonList.push_back( new Polygon ("red", 3)); // 3 sides so it will be a triangle

polygonList.push_back( new Polygon ("blue", 4)); // 4 sides so it will be a square

// The bottom two lines should give perimeter and area to triangle and square (should work all the way up to octagon/not implemented need guidance)

cout << "The area of shape 1 is > " << polygonList.at(0)->calculateArea() << " its perimeter is > " << polygonList.at(0)->calculatePerimeter() << endl;

cout << "The area of shape 2 is > " << polygonList.at(1)->calculateArea() << " its perimeter is > " << polygonList.at(1)->calculatePerimeter() << endl;

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions