Download

FVector2D explicit constructor

Hi,

I’m still learning C++ and I need some clarification on something that didn’t make sense to me. I stumbled on this issue as I was initializing some FVector2D using a float but as indicated here the constructor which takes in one float is marked as explicit which is fine.

This is the constructor declaration inside the FVector2D.h

explicit FORCEINLINE FVector2D(float InF);

My question is why is this possible and compiles without any errors ?

FVector2D MyVec = 15.f;

From my understanding this shouldn’t be possible due to the explicit constructor and should give a “no suitable constructor exists error” but it doesn’t or is there something I don’t understand ?

Thank you.

The Explicit keyword means you have be explicit, i.e. you have to write FVector2D(15.f);

Just writing 15.f would be an implicit conversion (not possible in this case anyway) - but you often write explicit constructors to avoid implicit conversions because they are unclear and generally frowned upon (or at least, they should be IMO).

Remember code clarity is much more important than short-hand.

Thanks for the answer, I understand the way the explicit keyword works and I agree on how important it is for clarity.

The issue is that this actually compiles and works, and I want to know why it does compile even though the construct is explicit.

FVector2D MyVec = 15.f;

Thank you, I’m using 4.26 if that’s important.

Somewhat horrifically, as pointed out by someone else - it’s possible that it’s using the implicit constructor of FIntPoint - so it’s a doubly-implicit conversion from float->FIntPoint->FVector2D.

If that’s the case, that’s a good lesson in why specifying the explicit keyword is so important. Though, you’d think the compiler was smart enough to see through this by now.

Got to love the inconsistency of code in UE at times.

1 Like

Oh that makes perfect sense, thank you so much for clarifying this, indeed this further proves the importance of the explicit keyword.

Cheers.

Update:
It’s exactly what’s happening as you suggested

> implicit conversion from float->FIntPoint->FVector2D.

Interestingly enough I tested this on a console C++ project that’s running C++14 and it did not allow me to compile, I’m wondering if it has to do with C++ version or some setting.