Search code examples
c++constructorambiguous

Overload resolution in a call with NULL as argument


I have two overloaded constructors:

Hello::Hello(std::string message)
{
}

Hello::Hello(int *number)
{
}

Either of those constructors can take a memory address. If I did Hello hi(NULL); then which would be called?

Also if you could explain the rules as they concern objects that are overloaded. Like similarly if I had one constructor that took a long for a parameter (Object::Object(long x)) and another overload (Object::Object(SomeOtherObject o)) that takes an object which itself had an overload for a long (SomeOtherObject::SomeOtherObject(long x)). Then I call Object obj((long)5); is it guaranteed to call one or the other?


Solution

  • Caling the std::string constructor would require an extra implicit conversion, so int* is preferred.

    For the second scenario, then the initial constructor is preferred. Why would the compiler look for any of the other constructors when it has a perfect match right there? And again, it includes an implicit conversion, which is worse than the perfect match the direct long constructor provides.