-2

we know that malloc gives unintialize memory, whereas calloc initialize memory with zero. So what value does new operator in c++ gives When it initialize the object??

  • 4
    It calls the object's default constructor. – BoBTFish Jul 27 '13 at 08:48
  • Also at compile time your object should be computed in size (with some exceptions), so it will allocate memory (in program heap as I remember) and call the constructor, I think. – Rolice Jul 27 '13 at 08:51
  • Try this if you're feeling masochistic: http://stackoverflow.com/a/620402/1171191 – BoBTFish Jul 27 '13 at 08:52

2 Answers2

5

Assuming there is a constructor for the object, it will call the default constructor.

But objects such as int, float, double, char, all forms of pointers, and such like, do not have default constructor [or an "empty" default constructor], so nothing gets done for those - you get whatever happens to be in the memory that new got for you - which may be zeros or some old gunk from a previous allocation.

You can, if you specifically want to, use the "value initialize" for memory block created by new, e.g. int *a = new int[size](); [zero initializes].

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

New basically calls an object constructor and its up to you how you want to initialize your object. If you don't initialize it, you will get garbage values on accessing

Saksham
  • 9,037
  • 7
  • 45
  • 73