Calling a constructor of the base class from a subclass' constructor body

前端 未结 4 1549
感动是毒
感动是毒 2020-12-15 10:07

I was under impression that it\'s impossible, see for example: Calling the constructor of the base class after some other instructions in C++
But the following program

4条回答
  •  暖寄归人
    2020-12-15 10:52

    You can't call it from the body of the child constructor, but you can put it into the initializer list:

    public:
        Child() : Person() { c = 1; }
    

    Of course it's not helpful to call the default constructor of the parent because that will happen automatically. It's more useful if you need to pass a parameter to the constructor.

    The reason you can't call the constructor from the body is because C++ guarantees the parent will be finished constructing before the child constructor starts.

提交回复
热议问题