What are the rules for calling the superclass constructor?

前端 未结 10 2177
甜味超标
甜味超标 2020-11-21 23:18

What are the C++ rules for calling the superclass constructor from a subclass one?

For example, I know in Java, you must do it as the first line of the subclass cons

10条回答
  •  死守一世寂寞
    2020-11-21 23:51

    If you have a constructor without arguments it will be called before the derived class constructor gets executed.

    If you want to call a base-constructor with arguments you have to explicitly write that in the derived constructor like this:

    class base
    {
      public:
      base (int arg)
      {
      }
    };
    
    class derived : public base
    {
      public:
      derived () : base (number)
      {
      }
    };
    

    You cannot construct a derived class without calling the parents constructor in C++. That either happens automatically if it's a non-arg C'tor, it happens if you call the derived constructor directly as shown above or your code won't compile.

提交回复
热议问题