Reputation: 79
I've got a superclass which has certain private variables, and I need to build a constructor for a subclass. Here's the superclass:
class Shape {
public:
Shape(double w, double h);
string toString();
private:
double width;
double height;
};
Superclass constructor:
Shape::Shape(double w, double h) {
width = w;
height = h;
}
Subclass:
class Rectangle : public Shape {
public:
Rectangle(double w, double h, int s);
string toString();
private:
int sides;
};
My subclass constructor is as follows:
Rectangle::Rectangle(double w, double h, int s) : Shape(w, h) {
width = w;
height = h;
sides = s;
}
I cannot modify the superclass at all. All I can do is modify the constructor class to get the values which are private in the superclass.
Upvotes: 0
Views: 2108
Reputation: 1051
If I understand it right, you want to modify superclass' private variables after they have been constructed via subclass.
Firstly, implement set()
methods in superclass so that we can access its private
variables:
Shape.h
class Shape {
public:
Shape(double w, double h);
string toString();
//here
setWidth(double);
setHeight(double);
private:
double width;
double height;
};
Shape.cpp
Shape::setWidth(double w) { width = w; }
Shape::setHeight(double h) { height = h; }
then, you can call superclass set()
methods via subclass:
Rectangle constructor:
Rectangle(double w, double h, int s)
: width(w) // subclass width
, height(h)
{
// modify subclass width & height as desired here
//then reflect superclass width & height according to subclass
Shape::setWidth(width);
Shape::setHeight(height);
}
Shape::setWidth()
and Shape::setHeight()
can be called wherever we want in subclass and superclass private
variables will be reflected accordingly.
Upvotes: 1
Reputation: 385164
The derived constructor is not responsible for setting width
and height
. Indeed, it can't even see them. You could make them protected
or even public
, but why? It's a good thing that only the base can manage its own members.
You're already specifying the arguments for the base constructor, so you're good to go. There's no problem here once you remove the redundant and broken lines:
struct Shape
{
Shape(double w, double h)
{
width = w;
height = h;
}
private:
double width;
double height;
};
struct Rectangle : Shape
{
Rectangle(double w, double h, int s)
: Shape(w, h)
{
sides = s;
}
private:
int sides;
};
As an aside, you should standardise on using the ctor-initialiser where possible, instead of using it only sometimes and then assignment from the body at other times:
struct Shape
{
Shape(double w, double h)
: width(w)
, height(h)
{}
private:
double width;
double height;
};
struct Rectangle : Shape
{
Rectangle(double w, double h, int s)
: Shape(w, h)
, sides(s)
{}
private:
int sides;
};
Upvotes: 2