Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded constructor - constructur with bool argument has precedence

I recently came across a class like the following

class Foo {
public:
    Foo(std::string msg) {}
private:
    Foo(bool b) {}
};

I noticed that trying to create an object of this class by means of

Foo foo("blah");

causes a compilation error telling that Foo::Foo(bool) is private. Apparently, if the argument is not an actual std::string, the compiler prefers to use the constructor with the bool argument. On the other hand, if the private constructor is not given, above code compiles just fine.

Why is it that the "bool-constructor" has precedence over the "string-constructor" althogh the type of the passed argument does not fit to any of them? Is this just a matter of definition or does it have a deeper meaning and some good reason?

like image 392
symphonic Avatar asked Mar 11 '13 15:03

symphonic


1 Answers

The reason has to do with conversion operator precedence. Each of the calls includes an implicit conversion

  1. pointer -> std::string
  2. pointer -> bool

In this case #1 is a user defined conversion and #2 is a language / compiler defined one. User defined conversions have a much lower precedence and hence the other conversion is preferred.

Edit

Here is a similar question which has a much more in depth explanation of the precedence checks involved

conversion precedence in c++

like image 128
JaredPar Avatar answered Nov 14 '22 21:11

JaredPar