What you have here are not pointers, but references. There are a few significant differences between the two. Firstly, references cannot be NULL
, they must point to something that has been initialized. Secondly, the syntax required is difference.
As an example, if you were using pointers, the function would have the signature:
void getTime(int* hours, int* minutes, int* seconds) const
{
hours = &hr;
minutes = &min;
seconds = &sec;
}
You'd then call it like so:
int hours, minutes, seconds;
hours = minutes = seconds = 0;
getTime(&hours, &minutes, &seconds);
References act in a similar way, that is, they are utilized to change the underlying argument that is passed in, as well as to avoid copying. The syntax is different, however:
int hours, minutes, seconds;
hours = minutes = seconds = 0;
getTime(hours, minutes, seconds); //Notice & not required
When would you utilize each? Generally, utilize references when you can, pointers when you must. In modern C++, pointers are often eschewed in favour of other constructs. They are still required for things such as polymorphism, or direct modification of values placed into containers (although this is most likely getting ahead of where you are, if none of this makes sense, just ignore it for now).
When passing a class or large object, utilize reference-to-const. So for example a std::vector
is usually passed as void some_func(const std::vector<int>& v)
. If you really need to modify it, pass by reference, void some_func(std::vector<int>& v)
.