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: C
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:
Shape
is set asideIn 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)
{ }