C++ calling base class constructors

后端 未结 6 1887
无人及你
无人及你 2020-12-08 00:23
#include 
#include  
using namespace std;

// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width =         


        
6条回答
  •  一整个雨季
    2020-12-08 00:55

    The short answer for this is, "because that's what the C++ standard specifies".

    Note that you can always specify a constructor that's different from the default, like so:

    class Shape  {
    
      Shape()  {...} //default constructor
      Shape(int h, int w) {....} //some custom constructor
    
    
    };
    
    class Rectangle : public Shape {
      Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call
    
    }
    

    The default constructor of the base class is called only if you don't specify which one to call.

提交回复
热议问题