-
Explicit keyword
What can I do? Something had to not get inside my thick skull. The explicit keyword is the one. Just can't get it.
Why is that the following code is working. Why does it allow the implicit conversion?
This is the class:
Code:
class Range {
public:
explicit Range(const int i): sInt_(i) {
if(i < 0 || i > 255)
throw std::out_of_range("Invalid small integer. Out of range.");
}
operator int() const { return sInt_; }
private:
size_t sInt_;
};
and on main...
Code:
double i = 12;
Range si(i);
-
It's allowing a conversion from double to int. That's different than a conversion from int to Range.
-
Yes. I was not clear and forgot to remove the operator int().
I mean exclusively the explicit defined construct. Shouldn't the explicit keyword on this case negate the implicit conversion from double to int?
-
That's what I was referring to. The explicit keyword on a constructor only governs conversions to the class to which it belongs.
-
If you want code:
Code:
void Foo(Range r)
{
//...
}
//...
double d = 5;
Foo(d); //error, asking for an implicit conversion
Foo(Range(d)); //no error (implicit conversion from double to int accepted)
-
Ah! Got it! Thank goodness.
Thanks both.