1

When I declare something like

int *i = new int;

what is the value it is initialized to (by the compiler). If I want to make sure it is zero would I have to use

int *i = new int(0);

will new initialize everything to zero?

on the same topic what will be initialized by the compiler what will have to be user (when it comes to pointers).

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

1 Answers1

2

These two declarations

int *i = new int;

int *i = new int(0);

are equivalent in the sense that the both allocate memory dynamically (in the heap). So the both pointers will be initialized. However the memory itself in the first case is not initialized and has some arbitrary value while in the second case the memory (that is the object of type int that was allocated) is initialized by 0.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Prefer "allocate memory dynamically" to "allocate on the heap". It's an uncertain and entirely irrelevant implementation detail whether the allocation happens "on the heap" or "on the stack" or anything else. What's important is the abstract semantics and the consequential behavior and/or correctness of the program. – The Paramagnetic Croissant Jul 07 '14 at 19:39