Given the following two constructor signatures, should it be possible to construct a Couple
with Couple("George", "Nora")
? My compiler complains with the error shown below. If I call it with Couple(std::string("George"), std::string("Nora"))
it compiles OK. I'm guessing there's an issue with the implicit casting which surprises me as I though char* to string would be fine.
class Person
{
public:
Person(const std::string& name);
};
class Couple
{
public:
Coordinate(const Person& p1, const Person& p2, const Optional<Person>& = Optional<Person>());
};
TestCouple.cpp:69: error: no matching function for call to `Couple::Couple(const char[7], const char[5])'
TestCouple.h:24: note: candidates are: Couple::Couple(const Person&, const Person&, const Optional<fox::Person>&)
In order for a user defined type (a class) to be implicitly convertible to another, there must be a constructor or conversion operator directly to that type. Implicit conversion (from user defined type to another) is not possible through an intermediate type.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
The word “implicit” means 'understood' or 'embedded'. In implicit C++ type casting, the data type in which the value is to be converted is not specified in the program. It is automatically done by the C++ compiler.
Indeed, a conversion sequence can't contain more than one implicit user-defined conversion; the standard specifies this in C++11 12.3/4:
At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.
In your case, two would be required (char const[]
to std::string
to Person
), and so implicit conversion is not possible.
You are correct that there is a problem with implicit conversion. It will only do one implicit conversion for a value, so you can do either Couple(std::string("a"), std::string("b"))
or Couple(Person("a"), Person("b"))
, for example, but Couple("a", "b")
would require the compiler to put in two implicit conversions per value. This is not allowed by the standard, because it would cause code that might be hard to understand correctly and be computationally expensive to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With