Home  >  Article  >  Backend Development  >  How Can I Delegate Constructors in C to Avoid Code Duplication?

How Can I Delegate Constructors in C to Avoid Code Duplication?

DDD
DDDOriginal
2024-11-22 06:40:14136browse

How Can I Delegate Constructors in C   to Avoid Code Duplication?

Delegating Constructors in C

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn