Alex Rivera | Logout

Why is a POD in a struct zero-initialized by an implicit constructor when creating an object in the heap or a temporary object in the stack?

Asked 2011-02-08T12:06:33.083
36

The standard and the C++ book say that the default constructor for class type members is called by the implicit generated default constructor, but built-in types are not initialized. However, in this test program I get unexpected results when allocating an object in the heap or when using a temporary object:

#include<iostream>


struct Container
{
    int n;
};

int main()
{
    Container c;
    std::cout << "[STACK] Num: " << c.n << std::endl;

    Container *pc = new Container();
    std::cout << "[HEAP]  Num: " << pc->n << std::endl;
    delete pc;

    Container tc = Container();
    std::cout << "[TEMP]  Num: " << tc.n << std::endl;

}

I get this output:

[STACK] Num: -1079504552
[HEAP]  Num: 0
[TEMP]  Num: 0

Is this some compiler specific behaviour? I don't really intend to rely on this, but I'm curious to know why this happens, specially for the third case.

Edit
Report

1 Answer

19

The short answer is: the empty parenthesis perform value initialization.

When you say Container *pc = new Container; instead, you will observe different behavior.

answered 2011-02-08T12:19:40.730

Your Answer