Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to have two implicit casts in constructing an object in C++?

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>&)
like image 310
Graeme Avatar asked Jun 25 '12 11:06

Graeme


People also ask

When can an implicit conversion occur between classes?

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.

What happens in implicit conversion?

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.

What is an implicit cast in C++?

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.


2 Answers

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.

like image 143
Mike Seymour Avatar answered Oct 09 '22 18:10

Mike Seymour


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.

like image 36
Magnus Hoff Avatar answered Oct 09 '22 17:10

Magnus Hoff