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?

21st Jan 2019, 8:39 PM
Cameron Hansen
Cameron Hansen - avatar
3 Antworten
+ 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.
22nd Jan 2019, 12:20 AM
Schindlabua
Schindlabua - avatar
+ 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.
29th Jan 2019, 3:35 PM
Cameron Hansen
Cameron Hansen - avatar
0
That was a very clear explination, Thank you!
22nd Jan 2019, 1:29 AM
Cameron Hansen
Cameron Hansen - avatar