Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate Constructor C++

Tags:

c++

c++11

Am I doing this right? I'm trying to delegate a C++ class constructor as it's basically the same code repeating 3 times.. I read up on C++x11 and read that g++ 4.7.2 allows this but I'm not sure if I'm doing it right:

Bitmap::Bitmap(HBITMAP Bmp) {    //Construct some bitmap stuff.. }  Bitmap::Bitmap(WORD ResourceID) {    HBITMAP BMP = (HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ResourceID), IMAGE_BITMAP, 0, 0, LR_SHARED);     Bitmap(BMP);   //Delegates to the above constructor? Or does this create a temporary? } 

OR do I need to do:

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)) { } 
like image 773
Brandon Avatar asked Dec 19 '12 20:12

Brandon


People also ask

What is delegate constructor?

Delegating constructors can call the target constructor to do the initialization. A delegating constructor can also be used as the target constructor of one or more delegating constructors. You can use this feature to make programs more readable and maintainable.

Can we create delegate to constructor in C#?

As phoog points out a constructor doesn't "return" a value; plus you get information about it with ConstructorInfo and not MethodInfo ; which means you can't create a delegate around it directly. You have to create code that invokes the constructor and returns the value. For example: var ctor = type.

What is the best description of constructor delegation?

Constructor Delegation in C++When a constructor calls other constructor of the same class, then it is called the constructor delegation.

How do you initialize a constructor?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.


1 Answers

You need to do the second. Delegating constructors only works in the constructor's initialization list, otherwise you'll just create a temporary or do other mistakes like you mentioned.

like image 143
Pubby Avatar answered Sep 27 '22 22:09

Pubby