PDA

View Full Version : Simple C++ question -- Creating a QPoint object



N3wb
17th September 2009, 03:39
I was trying to set the position of my program's window and had to use a QPoint object. It's working now, but I'm a little confused on something. I first tried to create the object like this:

QPoint windowPos = new QPoint(0, 0);

But that gave the error:

error: conversion from `QPoint*' to non-scalar type `QPoint' requested

I was able to get it to work with this line of code:

QPoint windowPos(0, 0);

But I don't understand why the first line didn't work. I thought that was the correct method for creating an object in C++?

I would appreciate someone explaining how my thinking is wrong, thanks :)

hasnatzaidi
17th September 2009, 05:09
hi, first u tell me that in which file where you used that code.?

lyuts
17th September 2009, 06:41
This is not correct


QPoint windowPos = new QPoint(0, 0);


You create and object that is supposed to be on stack as if it were an object to be on heap. Don't mix these things.

Do it this way


QPoint *windowPos = new QPoint(0, 0);

or


QPoint windowPos(0, 0);

scascio
17th September 2009, 09:04
Hi,



But that gave the error:


error: conversion from `QPoint*' to non-scalar type `QPoint' requested



The compiler message means that your are trying to affect a pointer to a QPoint (a QPoint*), to a QPoint. It is C++ basic features.

If you take time to decode (it is true it is not so clear as Java) messages, you'll find out what's happening

N3wb
17th September 2009, 14:59
So... This creates the QPoint on the heap:

QPoint *windowPos = new QPoint(0, 0);

And this creates it on the stack?

QPoint windowPos(0, 0);

scascio
17th September 2009, 15:09
You got it

lyuts
17th September 2009, 15:09
Yes, this is correct.

N3wb
17th September 2009, 15:18
Great, thanks!

Since the QPoint is something that is just needed temporarily, would it be better to create it on the stack?

And should I always create a widget on the heap?

scascio
17th September 2009, 16:19
For your case you should better allocate your QPoint on the stack, cause it is small

Generally, it depends on memory management and perfomance features.

hkvm
17th September 2009, 18:56
N3wb: You should really get a good book on C++ first, or try Python instead with some PyQt tutorials and stuff. Jumping into C++ like this is a recipe for very poor code a LOT of frustration.

wysota
17th September 2009, 20:12
Since the QPoint is something that is just needed temporarily, would it be better to create it on the stack?
Always create QPoint on the stack.


And should I always create a widget on the heap?
Yes, with exception of widgets that have (and you know will always have) no parents.