There is a time and a place for everything. In
class BIGRectangle: public Rectangle
{
public:
int area;
Rectangle.ResizeW(8);
Rectangle.ResizeH(4);
area = Rectangle.getArea();
};
the best place to initialize class members in is Member Initializer List of the constructor. For example:
class BIGRectangle: public Rectangle
{
public:
int area;
BIGRectangle():Rectangle(8, 4), area(getArea())
{
}
};
This says, build me a BIGRectangle
that is made of a Rectangle
that is 8 by 4 and stores the Rectangle
's computed area
.
But that requires Rectangle
to have a constructor that requires height and width.
class Rectangle: public Shape
{
public:
// no need for these because they hide the width and height of Shape
// int width = 2;
// int height = 1;
Rectangle(int width, int height): Shape(width, height)
{
}
int getArea()
{
return (width * height);
}
};
That addition builds a Rectangle
that uses Shape
's width
and height
rather than its own. When given two names in the same place, the compiler will pick the one declared inner most and hide the outer-most, and this leads to confusion and accidents. Rectangle
sees its width
and height
and needs help to see those defined in Shape
. Shape
has no clue that Rectangle
even exists because Rectangle
was defined after Shape
. As a result Shape
only sees its width
and height
.
This leads to some real nasty juju when you call getArea
. The current version sets Shape
's width
and height
and uses Rectangle
's width
and height
to compute the area. Not what you want to happen.
And that requires Shape to have a constructor that takes width and height
class Shape
{
public:
Shape(int inwidth,
int inheight): width(inwidth), height(inheight)
{
}
void ResizeW(int w)
{
width = w;
}
void ResizeH(int h)
{
height = h;
}
protected:
int width;
int height;
};
Note how the parameter is inwidth
, not width
. This isn't strictly necessary, but it's bad form to use the same name twice in the same place or close proximity for the same reasons as above: The same name in the same place at the same time is bad.
But this asks the question of what happens when you have Circle
which is a Shape
. Circles have no width or height, so you may want to rethink Shape
.