What are the rules for calling the superclass constructor?

前端 未结 10 2178
甜味超标
甜味超标 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:54

    In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:

    
    class A : public B
    {
    public:
      A(int a, int b, int c);
    private:
      int b_, c_;
    };
    

    Then, assuming B has a constructor which takes an int, A's constructor may look like this:

    
    A::A(int a, int b, int c) 
      : B(a), b_(b), c_(c) // initialization list
    {
      // do something
    }
    

    As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.

    Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.

提交回复
热议问题