I'm just getting into derived classes, and I'm working on the famous Shape
class. Shape
is the base class, then I have three derived classes: Circle
, Rectangle
, and Square
. Square
is a derived class of Rectangle
. I think I need to pass arguments from the derived class constructors to the base class constructor, but I'm not sure exactly how to do this. I want to set the dimensions for the shapes as I create them. Here is what I have for the base class and one derived class:
Shape(double w = 0, double h = 0, double r = 0)
{
width = w;
height = h;
radius = r;
}
class Rectangle : public Shape
{
public:
Rectangle(double w, double h) : Shape(double w, double h)
{
width = w;
height = h;
}
double area();
void display();
};
Am I on the right track here? I'm getting the following compiler error: expected primary expression before "double"
, in each of the derived constructors.
You have to change Shape(double w, double h)
to Shape(w, h)
. You are actually calling the base constructor here.
In addition, You don't have to set width
and height
in the constructor body of the derived class:
Rectangle(double w, double h) : Shape(w, h)
{}
is enough. This is because in your initializer list Shape(w, h)
will call the constructor of the base class (shape
), which will set these values for you.
When a derived object is created, the following will be executed:
- Memory for
Shape
is set aside
- The appropriate Base constructor is called
- The initialization list initializes variables
- The body of the constructor executes
- Control is returned to the caller
In your example, the Shape
subobject is initialized by Shape(double w = 0, double h = 0, double r = 0)
. In this process, all the members of the base part (width
, height
, radius
) are initialized by the base constructor. After that, the body of the derived constructor is executed, but you don't have to change anything here since all of them are taken care of by the base constructor.
Almost. Instead of redeclaring the parameters here:
Rectangle(double w, double h) : Shape(double w, double h)
You should simply "pass them through" (to give an inexact phrasing):
Rectangle(double w, double h) : Shape(w, h)
{ }