In this problem youll notice that the data members of the Sh
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. It should print out the same information, and in the same format, as the previous problem.
#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;
}
Solution
It is very easy. Just call base class to toString() to print parent class data and update child class aas you want.
string Rectangle::toString(){
stringstream ss;
ss = (( Shape *)this)->toString(); // call parent class function.
ss << \"sides: \" << sides<< endl;
}

