Can someone explain me what's is going on with this code.
class Point
{
private:
int x;
int y;
public:
Point(){}
void print(){
cout << x << " " << y << endl;
}
};
int main()
{
Point p;
p.print();
return 0;
}
If I run this code the output is -858993460 -858993460 witch is normal to me. It's garbage because I didn't initialize my 2 properties.
Here's the weird thing...
class Point
{
private:
int x;
int y;
int* buf;
public:
Point(){}
void print(){
cout << x << " " << y << " " << buf << endl;
}
};
int main()
{
Point p;
p.print();
return 0;
}
Now, I put the int* buf as a new class member and when I run this code, all my properties are initialized to zero. The output is 0 0 00000000. I'm using visual studio 2013 and I don't think this behavior was happening in Visual Studio 2010.
Can someone explain the logic behind that ?
Your class members are never initialized to zero, you need to do this yourself in your constructor
class Point
{
private:
int x;
int y;
public:
Point():x(0), y(0) {}
void print(){
cout << x << " " << y << endl;
}
};
If they are zero in your second example, then it is pure coincidence
When you print these int
s and the int*
you are printing the junk data that was in memory before these were allocated. Note that you are printing the address held by buf
not the value pointed to it. Printing *buf
will likely give you a segfault.
-858993460 in binary is: 11001100110011001100110011001100
It's possible that this is what your debugger in Visual Studio 2010 defaults memory locations to in order to warn you that you are reading bad data.
As far as the differences between 2010 and 2013, it's possible that you are no longer running in debug, or that your default debug block write in 2013 is just 0.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.