Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty string is interpreted as bool in Constructor

Tags:

c++

qt

Im am working on a QT project and have found a strange behaviour:

I have a class with several constructors that look like

DB_Variable(QString name, QString newValue):
name(name),value_string(newValue), var_type(DB_STRING){}

DB_Variable(QString name, bool newValue):
    name(name), value_bool(newValue), var_type(DB_BOOL){}

I now want to use the first constructor to create an object like this:

DB_Variable foo("some_name"," ");

I'd expect the empty string to be interpreted as a QString, but the second (bool) constructor is called. Can someone tell my why? Is the " " a pointer to an empty string and the then somehow rather a bool than a string?

Foo

like image 432
FooTheBar Avatar asked Feb 12 '23 15:02

FooTheBar


1 Answers

This problem results from implicit conversions going on in the constructor. String literals, such as the one in your code, are stored as const char types. Because you didn't have a constructor taking this type the compiler tries to find the conversion to a type that it can find in one of your constructors.

In this case const char* converts to bool easier that QString so when you do:

DB_Variable foo("some_name"," ");

The constructor

DB_Variable(QString name, bool newValue):

Is called.

Note that the behavior you are seeing isn't due to " " getting treated differently than any other string literal, it's just that you most likely didn't have a constructor with the types bool, bool (did all your constructors take a QString as the first argument?). Chances are if you had a constructor such as the following:

DB_Variable(bool test1, bool newValue):

Then this would have been called instead when you did something such as DB_Variable foo("some_name"," ");

To get the results you wanted you could pass in QStrings like so:

DB_Variable foo(QString("some_name"), QString());

Or perhaps define a constructor that takes const char* for the second parameter.

like image 165
shuttle87 Avatar answered Feb 24 '23 00:02

shuttle87