C++ Explicit Constructor
Asked Answered
D

2

5

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?

Drill answered 17/12, 2012 at 10:8 Comment(8)
AFAIK that should already be happening. Did you try it and it didn't work?Expound
yes I did try...it works only wheb i do like (size_t)30Drill
What happened? What was the error?Expound
no error, but when I debug I can see that the second ctor is being called.Drill
What happens in the following case MyClass obj( 30u );?Hypostasis
calls to the first ctor! :-) but I would like it to work even when not writing 30u.Drill
Remove explicit then. Explicit means the type must match exactly.Caducous
@Caducous no, that's not what explicit meansInaccurate
F
7

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.

Fistic answered 17/12, 2012 at 10:17 Comment(3)
Is there a way to make it work with like short, long long etc..?Drill
@TaruStolovich What do you mean? Have one explicit constructor that accepts all such literals? You can't, you'd have to overload the explicit constructor.Fistic
@DimaRudnik you can use std::enable_if with std::is_integral.Phantasm
G
0

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.

Geddes answered 2/3, 2019 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.