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

前端 未结 4 1547
感动是毒
感动是毒 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 11:00

    The following is an excerpt from "Accelerated C++": "Derived objects are constructed by:
    1. Allocating space for the entire object (base class members as well as derived class members);
    2. Calling the base-class constructor to initialize the base-class part of the object;
    3. Initializing the members of the derived class as directed by the constructor initializer;
    4. Executing the body of the derived-class constructor, if any."

    Summarizing the answers and comments: Calling a constructor of the base class from a subclass' constructor body is impossible in the sense that #2 above must precede #4. But we still can create a base object in the derived constructor body thus calling a base constructor. It will be an object different from the object being constructed with the currently executed derived constructor.

提交回复
热议问题