Re: Creating an instance of a class
On Feb 19, 9:16 am, "jimbo" <joachim.zett...@googlemail.com> wrote:
I am more or less new to c++ programing and therefore still have
problems with some fundamentals :(
At the moment I try to build a GUI-Application with Qt4. Sometimes I
have seen in the tutorials I have to instance a class with the new
command. Like QWidget QLabel *label = new QLabel("Hello World"); Then
I have created a pointer to a QLabel Object. The other way I have seen
is to just use QLabel label("Hello World"); Without a pointer and
without the new statement.
So to access the functions of the QLabel class I have to use the "."
for the part without pointer like label.show and for the pointer part:
Can somebody explain me, why it is possible to use the two ways and
what is the difference in general.
You really should get yourself a good book if you haven't got one
already because it can take some time to learn those things and there
are a lot of things to keep in mind which I can't explain in one post
(but you are always welcome to ask questions).
The difference between using 'QLabel label;' and QLabel* label = new
QLabel();' is where the instance is stored and its scope. When not
using new the instance will be created on the stack and will be
destructed when it goes out of scope (this usually coincide with a
When using new the object is created on the heap and will remain there
until you call delete on a pointer pointing to it. This means that an
object instantiated in one function using new can be used in another
function (even if the first function has returned) if given a pointer
For every time you create an object with new you must (for each and
every path of execution) call delete on a pointer to that object or
your object will leak memory. To make things a bit more trickier this
is not always true when using Qt since a parent object will usually
delete/destruct all child objects on destruction.
An advice regarding dynamically allocated memory (using new) is to not
use it unless you have to.