Question

I have a class with 2 constructors.

   explicit MyClass(size_t num);
   template<class T> MyClass(T myObj);

And I want that whenever I make

MyClass obj( 30 );

The first constructor will be called,

And on implicit constructors and

MyClass obj = 30;

The second ctor will be called.

How can I make it happen?

Was it helpful?

Solution

30 is a signed integer value, so it doesn't exactly fit the signature of your first constructor (therefore, the template gets instantiated).

You can either change the signature of the explicit constructor to accept an int, and than Myclass obj( 30 ); will call the explicit constructor, or call it with 30u so that you match the explicit signature.

OTHER TIPS

Regarding the first object

MyClass obj (30);

This is a direct initialization, thus the constructor should be called if the argument has a correct type of the parameter. In this case the parameter is incorrect so just to be more accurate in this case i would change the size_t to unsigned int and then pass 30u to this object. In this case the first constructor would be called. Regrding the second object

MyClass obj = 30;

This is an initialization by copy, thus i would change the second constructor to a copy constructor like this:

template<class T> MyClass(const T& myObj);

In my opinion in this case its even better to change your data members to ints. Nevertheless the first constructor should be called and then the second as wanted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top