Constructor Parameter Forwarding

Hi :)

My problem is this, and my apologies if the subject line doesn't describe my issue properly but it's the only way I could think of to describe it.

Maybe best to put some pseudo code... Lets say I have a Class called Image with an overloaded constructor... something like this..

Image::Image(UINT resourceID)
Image::Image(HMODULE hMod, UINT resourceID)

Now lets say I have Another Class called Surface that accepts a CONST Reference to an Image object... like so...

Surface::Surface(CONST Image& image)

Now... I know I can do this...

Surface * s = new Surface(someResourceID)

The object will be constructed using the single argument ::Ctor of Image

What I need is to be able to do this...

Surface * surface = new surface(someHModule, someResourceID);

and it should call the second constructor of Image. But that doesn't work or even compile.

Can someone please tell me if this is possible and if so... how to do it? :)
Does the Surface have an Image as base or member?
The compiler is only allowed to make implicit type conversions from 1 type.

Due to that reason, your first code works fine:

1
2
3
4
5
6
7
8
9
Image::Image(UINT resourceID);
Image::Image(HMODULE hMod, UINT resourceID);
Surface::Surface(CONST Image& image);

// 1 parameter
Surface * s = new Surface(someResourceID);

// 2 parameter
Surface * surface = new surface(someHModule, someResourceID);


Image has a 1-parameter constructor that is not declared explicit, therefore the compiler is allowed to invoke the int-parameter-constructor implicitly.
That means that your compiler convertes this code:
Surface * s = new Surface(someResourceID);
to this one:
Surface * s = new Surface(Image(someResourceID));

In your second example, you have 2 parameter.
The compiler is not allowed to make an implicit type conversion here and therefore the compilation fails.
To make the second line successful construct the image explicitly like this:

Surface * surface = new surface(Image(someHModule, someResourceID));

In c++11 you can make it with an initializer list: (note the brackets {})
Surface * surface = new surface({someHModule, someResourceID});
Last edited on
Topic archived. No new replies allowed.