2016-09-06 161 views
1

的順序考慮繼承和初始化

class A 
    { 
    }; 

class B 
    { 
    B(A * in); 
    }; 

class C : public A 
    { 
    B b; 
    public: 
    C():b(this){} 
    }; 

是在C安全構造? A的成員是否已經可用(和構建)?

+0

定義 「安全」 ... –

回答

4

是的。所有基類都是在執行構造函數的其餘部分之前構造的。

例如,從Stroustrup的C++ 2011的書:

17.2.3 Base and Member Destructors 
Constructors and destructors interact correctly with class hierarchies (§3.2.4, Chapter 20). A constructor 
builds a class object ‘‘from the bottom up’’: 
[1] first, the constructor invokes its base class constructors, 
[2] then, it invokes the member constructors, and 
[3] finally, it executes its own body. 
A destructor ‘‘tears down’’ an object in the reverse order: 
[1] first, the destructor executes its own body, 
[2] then, it invokes its member destructors, and 
[3] finally, it inv okes its base class destructors. 
+1

除了當'B'的構造函數試圖調用上'in'一個'virtual'功能。 – LogicStuff