In this problem, you\'ll notice that the data members of the Shape class are now
ID: 3681275 • Letter: I
Question
In this problem, you'll notice that the data members of the Shape class are now private instead of protected. This means that the child class no longer has direct access to them. We have added a toString method to the Shape class that can print these private variables, but it doesn't know anything about the child class sides variable. Use the parent Shape class' toString function to implement the Rectangle toString function.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Shape
{
public:
Shape(double w, double h);
string toString();
private:
double width;
double height;
};
Shape::Shape(double w, double h)
{
width = w;
height = h;
}
string Shape::toString()
{
stringstream ss;
ss << "Width: " << width << endl;
ss << "Height: " << height << endl;
return ss.str();
}
class Rectangle : public Shape
{
public:
Rectangle(double w, double h, int s);
string toString();
private:
int sides;
};
string Rectangle::toString()
{
//
// Implement the Rectangle toString function
// using the Shape toString function
}
// Use the constructor you created
// for the previous problem here
//
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 <sstream>
#include <string>
using namespace std;
class Shape
{
public:
Shape(double w, double h);
virtual string toString();
private:
double width;
double height;
};
Shape::Shape(double w, double h)
{
width = w;
height = h;
}
string Shape::toString()
{
stringstream ss;
ss << "Width: " << width << endl;
ss << "Height: " << height << endl;
return ss.str();
}
class Rectangle : public Shape
{
public:
Rectangle(double w, double h, int s);
virtual string toString();
private:
int sides;
};
string Rectangle::toString()
{
stringstream ss;
string base = Shape::toString();
ss<<base;
ss << "Side: " << sides << endl;
return ss.str();
}
Rectangle::Rectangle(double w, double h, int s):Shape(w,h){
sides = s;
}
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;
}
/*
Output:
1
2
Width: 1
Height: 2
Side: 4
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.