Reputation: 1
I am trying to print with a function from a function in a derived class with a function from the base class within it and I am not exactly sure if I should be how I can print out both information from the Shape toString function and 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
Shape::toString();
cout << toString();
stringstream ss;
ss << "Sides: " << sides << endl;
return ss.str();
}
// Use the constructor you created
// for the previous problem here
Rectangle::Rectangle(double w, double h, int s)
:Shape(w, h)
{
sides = s;
}
The only parts that can be manipulated in the problem are the sections that come after the comments
Upvotes: 0
Views: 220
Reputation: 1782
I think the problem is with this line:
cout << toString();
since it is going to recursively call itself and eventually you will run out of stack and get the runtime error.
your implementation should be:
string Rectangle::toString()
{
// Implement the Rectangle toString function
// using the Shape toString function
stringstream ss;
ss << Shape::toString();
ss << "Sides: " << sides << endl;
return ss.str();
}
Also consider making this method const
and virtual
in the case you want polymorphism to work properly.
Upvotes: 1