initial values of data members of objects on the stack vs heap
Hi,
I noticed a strange behaviour when converting my code from dynamically allocating objects to declaring the objects on the stack. It seems that members in dynamically allocated objects are initialized to zero, while members of objects declared on the stack carry random values. Is it defined behaviour or is it implementation specific? (I observed this behaviour with GCC 4.1 on Linux)
I wrote a simple test program as an example.
Code:
#include <iostream>
using std::cout;
using std::endl;
class A {
public:
int x;
};
int main() {
A *A_ptr = new A;
cout << A_ptr->x << endl; //always prints "0"
A a;
cout << a.x << endl; //prints a different value every time
}
Thank you very much.