Why did we use "new" operator here and what is the role of "new" operator in C++?
int *p = new int; //Here in this line
*p = 5;
cout << *p << endl;
delete p;
Why did we use "new" operator here and what is the role of "new" operator in C++?
int *p = new int; //Here in this line
*p = 5;
cout << *p << endl;
delete p;
In this particular example, there is no reason for dynamic allocation (which is what new
provides).
It looks like a toy example to show how you would dynamically allocate, set, print, then delete an int
.
In reality, you wouldn't do this unless you had a more complex type to create, or you really needed the int
to be shared between scopes for some reason (though, even then, smart pointers are nowadays preferred).
Refer to your book for more information on dynamic allocation and when it is (and isn't) useful.