0
When to use pointers vs references in c++
As I am writing my program in c++ classes, I don't fully understand when to use a pointer vs reference in my class fields and method parameters. How would I know when to use one or the other?
3 Answers
+ 1
Rule of thumb: Use const references wherever you can. And if you can't, use normal references. If you can't, use a pointer.
Sometimes you can't use a reference, for example references cannot be null, which is usually good but sometimes unwanted. Or sometimes you're working with outside code that uses pointers a lot.
Behind the scenes, a reference is just a const pointer!
PS: If you are dealing with primitive types like int, you usually want to pass by value rather than pointer or reference.
+ 1
I just wanted to add: After working with c++ for a little bit more, you get a feel for when to use pointers vs refrences; it just takes practice and over time feels intuitive. I'm still getting that intuitiveness but it's comming nonetheless. Cheers.
0
That was a very clear explination, Thank you!