Search code examples
c++pointersdynamic-memory-allocation

Cannot Understand the Meaning of new int(2)


As a C++ learner, this question might be a stupid one, so I really appreciate your patience and advice. I got the following piece of code from a book about programming:

int *ptr
ptr = new int(2)

So why do we put parenthesis for 2? I know "new int" represent dynamic memory, but what does it mean for "new int(2)"?


Solution

  • (2) is the initializer for the newly created int object. It has the same meaning as the initializer in a variable definition:

    int x(2);
    

    It initializes the object with the value 2.

    I suggest you use the brace-notation for initializers though, in most cases:

    int x{2};
    ptr = new int{2};
    

    (These two methods of initialization have subtle differences, but due to sometimes surprising parsing with () and other issues I would recommend that for most cases. It is a complicated topic and not without other opinions, though.)