Alex Rivera | Logout

Why is my overloaded C++ constructor not called?

Asked 2010-08-06T15:01:31.480
10

I have a class like this one:

class Test{
public:
  Test(string value);
  Test(bool value);

};

If I create an object like this:

Test test("Just a test...");

The bool constructor is called!

Anyone knows why?

Thanks

Edit
Report

3 Answers

8

This is a well known C++ annoyance.

Your string literal has type of chat const[]. You've got two constructors, conversion sequences from char const[] to Test look like this:

1) char const[] -> char const* -> bool

2) char const[] -> char const* -> std::string

1) is a built-in standard conversion whereas 2) is a user-defined conversion. Built-in conversions have precedence over user defined conversions, thus your string literal gets converted more easily to bool than to std::string.

answered 2010-08-06T15:09:00.143
4

The type of "Just a test..." is const char*. There is a built-in conversion from pointers to bool which is preferred over the non-built-in conversion from const char* to std::string.

The reason that the bool conversion is preferred is because std::string, while part of the standard library, is not a built-in type like integers, pointers, and booleans. It acts like any other class, and so its conversion constructors are considered only after conversions to built-in types.

answered 2010-08-06T15:06:46.960
0

One way is to create a variable of type std::string and pass the variable in:

std::string test = "TEST";
A a(test);

This way the type is explicitly defined as std::string it won't default to the constructor that accepts bool

answered 2010-08-06T16:22:00.687

Your Answer