nikitablack
nikitablack

Reputation: 4663

How the compiler chooses correct overloaded function?

I have a class with the following constructors:

Color(const float red = 0.0f, const float green = 0.0f, const float blue = 0.0f, const float alpha = 1.0f);
Color(const unsigned char red, const unsigned char green, const unsigned char blue, const unsigned char alpha);
Color(const unsigned long int color);

If I call it like this:

Color c{ 0.0f, 1.0f, 0.0f, 1.0f };

everything is ok. But if I call it:

Color c{ 78, 180, 84, 255 };

or

Color c{ 0xffffffff };

I receive

error C2668: 'Color::Color' : ambiguous call to overloaded function

Why? How to make it choose correctly?

Upvotes: 5

Views: 264

Answers (1)

Bathsheba
Bathsheba

Reputation: 234735

Color c{ 0.0f, 1.0f, 0.0f, 1.0f }; is unambiguous, the compiler can pick the constructor that takes floating point arguments.

With Color c{ 78, 180, 84, 255 };, the literals are actually signed types. So the compiler has to convert the literals. It has two choices and doesn't know which one to pick.

If you'd written, albeit tediously, Color c{static_cast<unsigned char>(78), static_cast<unsigned char>(180), static_cast<unsigned char>(84), static_cast<unsigned char>(255) }; then the constructor taking const unsigned char arguments would have been called automatically.

Again, with Color c{ 0xffffffff };, the number is again a signed hexadecimal literal. So the compiler doesn't know which one to use.

Upvotes: 4

Related Questions