code like this,
#include <iostream>
class obj
{
public:
int v;
};
int main(int argc, char *argv[])
{
obj o1;
std::cout << o1.v << std::endl; // print 32766, indeterminate values
obj *o2 = new obj();
std::cout << o2->v << std::endl; // print 0,but why?
int v1;
std::cout << v1 << std::endl; // print 22024, indeterminate values
int *v2 = new int;
std::cout << *v2 << std::endl; // print 0,but why?
return 0;
}
I know the global or static variables will be initialize zero.
and automatic does the indeterminate values.
but the heap object use new keyword, has any reference to explain it?
obj *o2 = new obj();
is value initialization meaning the object will be zero initialized and hence the data memberv
will be initialized to0
.This can be seen from value initialization:
On the other hand,
the above leads to undefined behavior because you're dereferencing
v2
and the allocatedint
object has is uninitialized and so has indeterminate value.Undefined behavior means anything can happen. But never rely(or make conclusions based) on the output of a program that has UB. The program may just crash.
This can be seen from default initialization: