c++ - 初始化变量之前是否调用了父类构造函数?

标签 c++ class inheritance

是在初始化变量之前调用父类的构造函数,还是编译器会先初始化类的变量?

例如:

class parent {
  int a;
public:
  parent() : a(123) {};
};

class child : public parent {
  int b;
public:
            // question: is parent constructor done before init b?
  child() : b(456), parent() {};
}

最佳答案

是的,基类在派生类的成员之前和构造函数体执行之前被初始化。

12.6.2 初始化基和成员 [class.base.init]

In a non-delegating constructor, initialization proceeds in the following order:

— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

— Finally, the compound-statement of the constructor body is executed.

关于c++ - 初始化变量之前是否调用了父类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366621/

相关文章:

c++ - OpenCV:如何对通过 calcOpticalFlowFarneback 获得的 vector 应用过滤器?

c++ - 为日期查找维度表填充加载文件的最佳方法是什么?

c++ - 如何为 ASCII 码 [C++] 初始化静态常量字符数组

c# - WPF 子控件,仅样式内容部分

javascript - 使用 javascript 原型(prototype)继承

C# - 为什么我需要在向下转换之前向上转换为对象?

c++ - 模板的非静态成员可以专用于数据或函数吗?

class - 如何实现案例类的实例共享

java - 如何创建正确的 Java 实例?

Java一步传递两个对象