Naitik
Naitik

Reputation: 65

Why use the "new" operator?

The code below is an example that was used to demonstrate some logic in C++

int *p = new int;
*p = 5;

cout << *p << endl;

delete p;

Upvotes: 1

Views: 288

Answers (1)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

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.

Upvotes: 5

Related Questions