When do you want to use pointers vs values in C++?

c++, pointers

Solution

C++ pointers operate exactly like Java objects, in that they may be invalid (`NULL`) and are cheap to pass to procedures.

C++ references are a thin wrapper around pointers. They're not supposed to be invalid, but in some cases may be. For example, a reference might be created from a `NULL` pointer, or the memory it references might be deleted.

In the code example you give:

Employee boss("Frank");

you are using something called a "value". Unlike pointers and references, values are the object they represent, not an indirection.

My question is, when is it appropriate to use Pointers VS [values]? What is the best practice? How should I know in what way I want to declare my variables most of the time?

C++ doesn't have garbage collection, so values are used when the scope of a variable is limited. For example, instead of allocating one with `new` and deallocating with `delete` for every variable in a procedure, you can allocate them on the stack and not worry about the memory.

Problem

I'm coming from Java and attempting to learn C++. As far as I can tell, using Pointers is very similar to how reference variables work in Java, in that you pass a memory address to the value. So I feel like I have gotten a pretty good understanding of them. I also understand that these variables are stored on the heap. However, I see that there is another way in which you can declare variables in C++, without the new operator/pointers simply doing something like: ``` Employee boss("Frank"); ``` Which will create a value of Employee with "Frank" as the parameter. These variables are stored on the stack. So, you have these 2 very different ways of creating variables and both with their own unique behavior (with memory management as well?). My question is, when is it appropriate to use pointers VS values? What is the best practice? How should I know in what way I want to declare my variables most of the time?

Original source

Related problems