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