I know the basics of pointers.
I would just like to know when you would use
Foo *foo;
instead of
Foo foo;
and what one allows you to do that the other doesn't.
Thanks in advance
I know the basics of pointers.
I would just like to know when you would use
Foo *foo;
instead of
Foo foo;
and what one allows you to do that the other doesn't.
Thanks in advance
You typically use pointers if you want to refer to heap variables (object survives end of function), and the non-pointer form for local variables (lifetime ends with block/function).
As a member variable, you use pointers if you share Foo objects across different referrers, and you use embedded objects if you have a whole-part relationship with Foo.
If that's a variable declaration, Foo *foo; declares a variable of type pointer-to-Foo. Foo foo declares a variable of type Foo.
See wikipedia's article on pointers for more info.
Read the chosen answer to this question, is very intuitive: http://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome/5754
you use Foo * foo
in many cases :
1 - if the returned value is an array of type Foo
2 - if the function manipulates some data structure (especially if you are working with a functional paradigm where the only result of a function is it's returned value) ex :
List * deleteListNode(int nbr, List * src) {
Node * tmp = getElementPointer(nbr, src);
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
return src;
}
this function takes as arguments the number of an element in a list and a list and it return a pointer to the same list token as an argument after deleting the desired element, so the function does manipulate only pointer which as you know are 32 bits values (or maybe 64 bits on 64 bits systems).
3 - if the creation of the returned object is resource consuming so you would return a pointer to the existing object, especially in creation functions ex : List * createList
, Tree * createTree
... because you do create your data structure inside the function so it is existing in the memory all you have to is to return it's address