Does memory allocated for built-in types (in particular int, float and double) with the new operator initialize them to 0 (or 0.0, as the case may be)? Just trying to remember. (I seem to remember that new invokes a constructor even for the built-in types, but i'm not sure).

Recommended Answers

All 4 Replies

No.

Proof:

int main()
{
    int* n = new int;
    cout << *n << "\n";
}

hm, are you sure, I'm getting n as 0 with the above code? (which is what i would expect from initialization). I'm using g++ 4.3.3 btw, if it makes any difference.

The value could be anything -- I got 23 with vc++ 2008 express and 3346328 with Code::Blocks (MinGW). It all depends on what was in that memory location.

I guess that makes sense... thanks.
It seems we can specify an initializer in constructor style:

int * n = new int(0)

but since (from what i just read) this doesn't work with arrays, it doesn't help with what i had in mind.
Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.