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
A copy constructor can also be defined by a user; in this case, the default copy constructor is not called. A user-defined copy constructor is generally needed when an object owns pointers or non-shareable references to a file (for example).
Overloaded constructors essentially have the same name (exact name of the class) and different by number and type of arguments. A constructor is called depending upon the number and type of arguments passed. While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.
The type of "Just a test..."
is const char *
, which can be implicitly converted to either bool
or std::string
. Because std::string
isn't a built in type, the const char *
s is converted to a bool
. You can prevent that by explicitly converting the const char *
to a std::string
:
Test test(std::string("Just a test..."));
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.
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