0

I cannot understand why std::string converted into QString while passing it to constructor. Here is small example:

  class StringHandler
 {
 private:
     QString str;
 public:
     StringHandler(QString s): str(s) {}
  };

 int main(int argc, char *argv[])
 {
    QCoreApplication a(argc, argv);

    std::string str = "string";
    QString qstr(str); // it gives error there are no constructor QString(std::string)
    StringHandler handler(QString(str));//it does not give an error. Why?

    return a.exec();
 }

EDIT:

class StringHandler
{
public:
    StringHandler(QString s): str(s) {}
    QString str;
};

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

std::string str = "string";
StringHandler handler(QString(str));//Here should be error, but there no error. Why?
qDebug()<<handler.str; //Error is here: request for member 'str' in 'handler', which is of non-class type 'StringHandler(QString)'

return a.exec();
}
11
  • 1
    add the actual error output, please. Commented Oct 18, 2015 at 10:02
  • possible duplicate of How to change string into QString? Commented Oct 18, 2015 at 10:03
  • @zenith The problem is not about error. I don.t understand why this line:StringHandler handler(QString(str)) works. Commented Oct 18, 2015 at 10:05
  • 2
    And does it compile if you remove the QString qstr(str); line and just leave the other one? Commented Oct 18, 2015 at 10:06
  • 1
    Really, we need the compiler error that you get in the non-working state. This normally should not work. Commented Oct 18, 2015 at 10:09

1 Answer 1

3

Say hello to the most vexing parse.

StringHandler handler(QString(str)); declares a function named handler that takes a QString and returns a StringHandler. Yes. Thanks to the C++ parsing rules.

Now the error message request for member 'str' in 'handler', which is of non-class type 'StringHandler(QString)' makes sense: handler is being treated like a function of type StringHandler(QString) and you're trying to access a member named str in it, but of course functions have no members so the compilation fails.

You can fix this by using the uniform initialization syntax:

StringHandler handler{QString(str)};

The above can't be parsed as a function declaration, and so the compilation should fail for the expected reason: no matching constructor QString(std::string).

For more info, see C++'s most vexing parse again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.