C++ – Convert QString to Pointer of QString

c++, pointers, qt, string

As i am no C(++) expert i am stumped by some stubbornness of the compiler not wanting to convert a, in this case, QString to a QString*.
I have a function:

bool getNextMessage(int sId, QString *msg, QString *cmd)

I am using pointers here because i can not return more than one variable (spoiled Perl coder 😉 ) in C and i want to use this in a while(getNextMessage(…)){…} style loop.
Inside that function there is some SQL foo and this:

 msg = QString(""); cmd = QString(""); return false;

All that the compiler produces from this is this:

 cannot convert 'QString' to 'QString*' in assignment

Could you dear folks please lift the mystery for me? Thanks. 🙂

EDIT:
Solution: Using references now thanks to the pointer to them from leemes.

Best Solution

For this you typically use references, not pointers. For C++ newbies, it's hard to get what the difference is. A short explanation would be "references are safer pointers".

bool getNextMessage(int sId, QString &msg, QString &cmd)

This way, you can call the method without converting to pointers before and use the references with the same syntax as you work with normal variables, so your code for setting the content of the strings is fine.

If you want to stick to pointers -- or, to understand how to do it with pointers -- this is how you work with pointers:

*msg = QString("");

*msg dereferences msg, meaning that you are working with the object behind the pointer. For function calls, there is the -> operator.

Calling

msg = new QString("");

would be syntactically correct too, but doesn't do what you expect it to do! This line means that you allocate a new QString object and get a pointer of this newly created object. Then, you assign this pointer to msg. This is fine for following code within the function. However, you changed msg itself (the pointer address) and not the memory where msg points to. This means, that the caller won't notice anything here. The caller works with the old pointer after the function call.