Home > Article > Backend Development > How Can I Delegate Constructors in C to Avoid Code Duplication?
When dealing with multiple constructors in a C class, there may be instances where the same code is repeated across constructors. To streamline this process, C provides the ability to delegate constructor calls.
In your scenario, you are trying to call the Bitmap(HBITMAP) constructor from the Bitmap(WORD) constructor. While your first approach creates a temporary bitmap and calls the other constructor with it, the correct syntax for constructor delegation is using the constructor initialization list.
The following code demonstrates the correct approach:
Bitmap::Bitmap(HBITMAP Bmp) { // Construct some bitmap stuff.. } Bitmap::Bitmap(WORD ResourceID) : Bitmap((HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ResourceID), IMAGE_BITMAP, 0, 0, LR_SHARED)) { }
By placing the constructor delegation call in the initialization list, you ensure that the Bitmap(HBITMAP) constructor is called before any other statements in the Bitmap(WORD) constructor. This allows you to reuse the common code while initializing the Bitmap object with different parameters.
The above is the detailed content of How Can I Delegate Constructors in C to Avoid Code Duplication?. For more information, please follow other related articles on the PHP Chinese website!