When to use a pointer to a class and when to instantiate it as a variable

advertisements

Im sort of confused by it. The best I could find was reading through the cplusplus.com tutorial and all they have to say about pointers to classes.

"It is perfectly valid to create pointers that point to classes. We simply have to consider that once declared, a class becomes a valid type, so we can use the class name as the type for the pointer"

Which tells me nothing about when to use them over the normal instantiation. I've seen the -> operator many times, and looked at some codes but cant really decipher why they did it.

Generic examples will be appreciated; but more specifically related to gui programming. Its where I encountered it first.

QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(nameLabel, 0, 0);
mainLayout->addWidget(nameLine, 0, 1);
mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);
mainLayout->addWidget(addressText, 1, 1);

Why not

QGridLayout mainLayout
mainLayout.addWidget
...

(It doesnt compile if I change the sample code to that and try it but you get the point)

Thanks in advance


A good way to think about when to stack-allocate (non-pointer) versus heap-allocate (pointer) an object is to think about how long you want that object to live. If you put the object on the stack as a local variable, then it will be cleaned up and cease to exist as soon as the function returns. If you want the object to outlive the function call that created it, put it on the heap.

With the example of the grid layout, I believe that the pointer version is more appropriate because after the function call that creates the layout returns, you still want to have the layout lying around. Otherwise, the layout would exist only as long as the function was running.