10/01/2008

default constructor

C++中預設建構子就是沒有參數的建構子

一般大多數人都有以下錯誤觀念:
1.class沒有定義預設建構子 compiler就會自動產生一個
2.compiler產生出來的預設建構子中 會為member data設預設值

在C++ standard(ISO/IEC 14882)中說明:
"The implementation will implicitly declare these member functions for a class type when the program does not explicitly declare them, except as noted in 12.1. The implementation will implicitly define them if they are used"

當compiler有需要而又沒有時才會產生出來 所以沒需要時就不會產生

那甚麼時候需要呢! 文件中說明:
"If there is no user-declared constructor for class X, a default constructor is implicitly declared. An implicitly-declared default constructor is an inline public member of its class. A constructor is trivial if it is an implicitly-declared default constructor and if: — its class has no virtual functions (10.3) and no virtual base classes (10.1), and — all the direct base classes of its class have trivial constructors, and — for all the nonstatic data members of its class that are of class type (or array thereof), each such class has a trivial constructor. Otherwise, the constructor is non-trivial."

所以說需要的定義取決於 1.virtual functions, 2.virtual inherited, 3.base class and 4.data members.

1.virtual functions
當一個類別定義virtual functions後,每一個物件都必須有一個virtual function table記錄virtual function的位址,因此compiler會自動擴張物件的data member,產生這個table並且加入一個指標指向這個table。

2.virtual inherited
(待補)

3.base class
當一個class沒有任何預設建構子而它的base class有預設建構子時,那麼必須需呼叫base class的預設建構子,所以compiler自動擴張一個預設建構子,其中呼叫bass class的建構子。

如果存在建構子的話,compiler會擴張建構子做上述事情而不擴張一個預設建構子。文件的解析是由於使用者定義的建構子存在下就不會隱含產生預設建構子。

4.data members
同理。當data member中,存在至少一個物件有預設建構子時。

沒有留言: