Constructor Delegation in C
In C , it is possible to delegate one constructor to another, allowing the reuse of initialization code across multiple constructors. This practice can simplify code and reduce repetition.
One method to accomplish constructor delegation is through the constructor's initialization list, as shown in the second example you provided:
Bitmap::Bitmap(WORD ResourceID) : Bitmap((HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ResourceID), IMAGE_BITMAP, 0, 0, LR_SHARED)) { }
In this example, the constructor for Bitmap(WORD ResourceID) delegates to Bitmap(HBITMAP), passing the loaded image as an argument to the delegated constructor. This syntax ensures that the Bitmap(WORD ResourceID) constructor does not create a temporary variable or perform unnecessary duplicate initialization.
The alternative approach, which you questioned in your first example, would indeed create a temporary Bitmap object and then call the constructor of that object with the HBITMAP passed to Bitmap(WORD ResourceID). While this may work in some cases, it is not the most efficient or correct way to delegate constructors.
Therefore, it is recommended to use the constructor's initialization list for constructor delegation, as illustrated in the second code snippet you provided. This ensures efficient and proper initialization of the object being constructed. G 4.7.2 and later versions should support this feature.
The above is the detailed content of How Can Constructor Delegation Be Efficiently Implemented in C ?. For more information, please follow other related articles on the PHP Chinese website!