I am working on learning a little about pointers in c++. I get not get my head around the ways in which pointers are declared. The book initializes the pointer declaration by first using an asterisk sign prior to a pointer variable.
int *p;
After then it is required to initialize a new variable in the heap using the "new" operator and then assign value by dereferencing the pointer.
p = new int;
*p = 45;
Now there are some examples in the book where the writer does all of the work in a single statement using the following code,
int *p = new int;
*p = 45;
It is quite confusing. How can we assign a new int to *p because we have to assign the value to *p, as in the first case?
P.S : I have tested the second case in the compiler and it works like a charm. But i can not get my head around it.
int i = 5;, except instead ofint, you have anint *, and instead of 5, you allocate memory and initialize the pointer to the location of that memory.*. In practice, you have smart pointers likestd::shared_ptr<int> p = new int;, and furthermore they appear as class members, and are initialized in the constructor (your C++ course might cover things in a different order, but a good course should not start withint *p.