Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my overloaded C++ constructor not called?

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

like image 993
user413185 Avatar asked Aug 06 '10 15:08

user413185


People also ask

When a copy constructor is not called?

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).

How do you know if a constructor is overloaded?

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.

Can constructor be overloaded or not?

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.


2 Answers

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..."));
like image 63
Bill Carey Avatar answered Sep 29 '22 08:09

Bill Carey


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.

like image 22
Maxim Egorushkin Avatar answered Sep 29 '22 08:09

Maxim Egorushkin