I'm learning C++ and don't really see why I'd use a pointer instead of just writing the variable's name. What does a pointer let me do that the name doesn't?
Why do we need pointers when we already have variable names?
Answers
If you have an int called n and write int* p = &n, then *p accesses n. In that tiny example, using n directly is simpler. The pointer hasn't bought you much.
The useful part is that p can be changed to point to a different int while the program runs. Code using *p can then work with whichever object p currently points to, without needing to know its name.
Reply to this answer
Think about a function that needs to work with an object owned by its caller. Passing a pointer lets the function access that same object rather than receiving a separate copy. It can also let the function change the caller's object.
In C++, a reference often makes more sense for this. Use a const reference when you want to avoid copying but don't need to change the object. A pointer can be useful when there might be no object, represented by nullptr, or when the pointer needs to point somewhere else later.
Reply to this answer
Not every object you work with has a convenient variable name in your source code. A program might create objects at runtime, and pointers can keep track of where those objects are.
That doesn't mean you need to write new and delete everywhere. In modern C++, containers such as std::vector and smart pointers handle many of those jobs for you. You'll still run into pointers when learning how things work or using certain APIs.
Reply to this answer
For a beginner, it's fine if pointers feel unnecessary in the examples you've seen. Plenty of straightforward C++ code works well with ordinary variables and references. Learn what a pointer stores and how to use one safely, but don't feel obliged to put one in every program.
Reply to this answer
Add your answer
Answers are reviewed before publication.
7b+socketwinder_293:
So the pointer is like a variable for choosing which object to access?
_b71+claspgauge.9:
Yes. Just make sure it points to a valid object before using *p. A null pointer, for example, doesn't point to an object you can access.