I have a kinda deep C experience but I am a C++ beginner. References seem to be easier to use than pointers, but it drives me crazy. I think all references can be replaced with pointers. In my case, pointers are not that hard because I spent tons of times studying them. Is it common among C++ programmers to use references or is it just recommended??
Asked
Active
Viewed 99 times
-2
-
IMO references vs pointers is a style issue, and as such, there is no right answer. – user253751 May 31 '15 at 03:48
-
In some cases (like copy constructors and some overloaded operators), references are necessary. But if you know pointer really well, I don´t see why it is a problem. – deviantfan May 31 '15 at 03:53
2 Answers
1
One thing that references prevent is NULL
pointers. If you want to ensure that a parameter passed to a function is not NULL, you can pass by reference.
void func(int& i); // i cannot be NULL

Daniel
- 6,595
- 9
- 38
- 70
1
References cannot always be replaced by pointers:
C a, b, c;
a = b - c;
If there is an operator-()
for C
, it either needs to receive its arguments:
by copy:
C operator-(C left, C right);
by address:
C operator-(C* left, C* right);
in which case the call becomes:
a = &b - &c;
(which already has a meaning in C)
or by using a new construct that has no equivalent in C. This became references in C++.
There are a variety of questions you can refer to concerning the use of references versus pointers.