Does i need to use pointer only if I want to delete it and free the memory from it and its addres too, as i dont want memory leaks? |
Yes, but think of it this way.
You went to the heap as said, "Can I have an int?" The heap makes one up and gives you its address. So, when you're done, you're expected to give it back. That's what new/delete do.
You need to put this int somewhere, and the place to store it is in a variable of type
pointer to an int. But that pointer is just another variable.
Not all pointers point to objects from the heap. But if the heap gives you an object, you are expected to give it back when you're done with it.
Pointers are used to create dynamic memory? |
No. Pointers can be used to store the address of objects form the heap, plus other stuff.
Does the simple variable from V1 is delete and free? |
No. In V1, when make the declaration:
the compiler creates space on the runtime stack for the int. When the function returns, the space is released automatically. That's why such variables are called automatic variables.
Does we need to replace simple variable to pointer for small amount of used memory? |
There are two levels to this. First, you need to understand how the mechanism works. Second, you need to understand how the feature is used. There are two different things.
Let's take another look.
V1 uses an int that's created on the stack. Space for it is automatically created for it on the stack by the language. The space is released automatically when the function returns.
V2 uses an int that's created on the heap. Space for it is manually requested and it must be manually returned to the heap.
That's how it works. But why might you need to use it?
C++ supports procedural and object oriented programming. The two paradigms are different and demand different treatment of things.
Procedural programming tends to used user defined types directly. Pointers are used, but only to suit the task at hand.
Object oriented programming in C++ only works thru pointers. So if you're doing object oriented programming in C++, object should be allocated dynamically and
must be used via pointers (or references).
So learn the basics first because you'll need them later. If you don't you'll be forever confused.