Pointers to Structures and Objects

Hi all.

So, I 80% comprehend what a pointer is all about.

But, what is the use of pointers to structures or objects?

When do these come in handy (when is it a must (or a better option) to use them)?
If you've got to use the object in another function, I always think it's best to work with pointers. Copy constructors are a pain and are the root of almost every single one of my return-from-function errors. However, of course, there are a few occasions where you want to make sure the data within your object is secure, in which case it is best to avoid pointers and use the copy-constructor. Do it right and it'll be the real object's twin brother, ready to be butchered and slaughtered, all while the original is safe at home, waiting for the results of the function.
My canned response:

Pointers should be used when the object needs to live beyond the scope in which it is declared.

(Copy constructors are extraordinarily useful. If you avoid using pointers, ironically, you don't
even need to write a copy constructor; the default member-wise copy version is almost always
adequate in other cases).
Additionally, if the pointer will always point to an object (ie is never null) a reference could be used. Personally, I prefer references over pointers whenever possible; I think it makes the indirection more transparent (not a big deal, though).

EDIT: Actually, when it comes to function parameters that will be returning a value, using a pointer rather than a reference would make the call itself explicitly identify the return parameters. It's kind of neat:
bool f1( string input, int & ret ) { /* change ret and return status */ }
bool f2( string input, int * ret ) { /* change *ret and return status */ }
bool status;
string in = "some kind of input, etc.";
int ret;

status = f1( in, ret );
// vs.
status = f2( in, &ret );
Last edited on
Topic archived. No new replies allowed.