1

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
difference between a pointer and reference parameter?

I keep running into the same question: In C++, e.g. when setting-up a new class, when should I use pointers and when references?

Should I always prefer references over pointers?

What I don't really understand is, aren't references implemented as pointers anyway?

Community
  • 1
  • 1
Ben
  • 15,938
  • 19
  • 92
  • 138

2 Answers2

1

The fact that references might be implemented as pointers doesn't really come into it in my opinion.

My personal rule of thumb is - if whatever you pass in has to be present, use a reference as references always have to be bound to an object. If whatever you are passing around may be present but isn't guaranteed to, use a pointer and make sure it's a non-null pointer before you use it.

Timo Geusch
  • 24,095
  • 5
  • 52
  • 70
1

Yes always prefer references. References are aliases. Yes you can think of them as constant pointers. You can't do any pointer arithmetic on the so they are generally much safer as a callee method cannot mess them up. You don't have to check for null references either in the callee as it's not a pointer. It's a reference and hence can't be null. It has to be an alias to something. So yeah, unless you have a solid reason to use pointers, just go with references.

Sid
  • 7,511
  • 2
  • 28
  • 41