When do we need to have a default constructor?

A default constructor is not synthesised if you created your own constructor with arguments. Since you gave Shape a constructor of your own, you’d have to explicitly write out a default Shape constructor now:

class Shape
{
      int k;

  public:
      Shape() : k(0) {}
      Shape(int n) : k(n) {}
      ~Shape() {}
};

(You can leave out the empty ~Rect() {} definitions, as these will be synthesised.)

However, it looks to me like you don’t want a default constructor for Shape here. Have Rect construct the Shape base properly:

class Shape
{
      int area; // I've had to guess at what this member means. What is "k"?!

  public:
      Shape(const int area)
         : area(area)
      {}
};

class Rect : public Shape
{
     int l;
     int w;

  public:
     Rect(const int l, const int w)
        : Shape(l*w)
        , l(l)
        , w(w)
     {}
};

Also note that this example is oft cited as an abuse of OO. Consider whether you really need inheritance here.

Leave a Comment