I need help with this simple coding activity. I will award full points to the fi
ID: 647329 • Letter: I
Question
I need help with this simple coding activity. I will award full points to the first person whos code works
"We have provided you with a Shape parent class, and a Rectangle class that inherits from it. Implement the Rectangle constructor."
#include
#include
#include
using namespace std;
class Shape
{
public:
Shape(double w, double h);
protected:
double width;
double height;
};
Shape::Shape(double w, double h)
{
width = w;
height = h;
}
class Rectangle : public Shape
{
public:
Rectangle(double w, double h, int s);
string toString();
private:
int sides;
};
string Rectangle::toString()
{
stringstream ss;
ss << "Width: " << width << endl;
ss << "Height: " << height << endl;
ss << "Sides: " << sides << endl;
return ss.str();
}
//
//CODE HERE -- Using the Shape class constructor implement the Rectangle constructor
//
int main()
{
double width;
double height;
const int sides = 4;
cin >> width;
cin >> height;
Rectangle bob = Rectangle(width, height, sides);
cout << bob.toString();
return 0;
}
Explanation / Answer
#include <iostream>
#include <stdio.h>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
Shape()
{
printf("creating shape ");
}
Shape(int h,int w)
{
height = h;
width = w;
printf("creatig shape with attributes ");
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
Rectangle()
{
printf("creating rectangle ");
}
Rectangle(int h,int w)
{
printf("creating rectangle with attributes ");
height = h;
width = w;
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
Rectangle *square = new Rectangle(5,5);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
Output of the above is:
creating shape
creating rectangle
creating shape
creating rectangle with attributes
Total area: 35