When do we need to have a default constructor?

后端 未结 7 1372
终归单人心
终归单人心 2020-12-08 14:43

My question is simple. When do we need to have a default constructor? Please refer to the code below:

class Shape
{
    int k;

public:
    Shape(int n) : k         


        
7条回答
  •  广开言路
    2020-12-08 15:03

    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.

提交回复
热议问题