Search code examples
c++pointersnew-operator

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;

Solution

  • 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.