C++ Objects: When should I use pointer or reference
I just came from Java and is new to C++. Over the course of a month, I managed to teach myself C++. I've coded some basic stuff here and there, and understand some of the concepts (Polymorphism, Virtual Functions etc). Although I know how Pointers work, I'm still having trouble knowing WHEN to use them.
I know that when you want to create something out on the heap using new, you have to use a pointer, but I fail to recognize other situations in which pointers and references should be used. Is there some sort of rule of thumb on when to use pointers I should know about? Like when should function parameters have & or * in them etc. Sorry for the noob question.
Same answer in other So question (http://stackoverflow.com/questions/7058339/c-when-to-use-references-vs-pointers):
Use reference wherever you can, pointers wherever you must.
Avoid pointers until you can't.
The reason is that pointers makes things harder to follow/read, less safe and far more dangerous manipulations than any other constructs.
So the rule of thumbs is to use pointers only if there is no other choice.
For example, returning a pointer to an object is a valid option when the function can return nullptr in some cases and it is assumed it will. That said, a better option would be to use something similar to boost::optional.
Another example is to use pointers to raw memory for specific memory manipulations. That should be hidden and localized in very narrow parts of the code, to help limit the dangerous part of the whole code base.
In your example, there is no point in using a pointer as parameter because :
if you provide nullptr as parameter, you're going in undefined-behaviour-land; the reference attribute version don't allow (without easy to spot tricks) the problem with 1. the reference attribute version is simpler to understand for the user : you have to provide a valid object, not something that could be null. If the behaviour of the function would have to work with or without a given object, then using a pointer as attribute suggest that you can pass nullptr as parameter and it is fine for the function. That's a kind of contract between the user and the implementation code.