lundi 23 mai 2022

the difference of automatic and dynamic variables rules in zero initialization

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?

Aucun commentaire:

Enregistrer un commentaire