Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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

like image 919
Guillaume Avatar asked Jan 04 '11 22:01

Guillaume


2 Answers

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.

like image 62
templatetypedef Avatar answered Oct 13 '22 08:10

templatetypedef


One good reason is polymorphism and dynamic dispatching. By having a pointer declared to a base class type and assigning it to an instance of a subtype, you could be invoking different versions of the method. In the above examples, there is probably some base type (maybe QTLayout?) with which the pointer can be declared.

Another reason is a situation where you want your object to "live" beyond the scope of the method in which it is declared. Your second example is allocated on the stack and will be deallocated when you leave.

like image 37
Uri Avatar answered Oct 13 '22 09:10

Uri