0

There may be other examples, but this is the one I just came across.

#include <iostream>
using namespace std;

class Student
{
  public:
    int x; 
};

int main()
{
  Student rts;
  Student* heap = new Student;

  cout << rts.x   << endl; // prints out random integer
  cout << heap->x << endl; // prints out 0
}

Is there any good reason or logic to understand behind this?

trincot
  • 317,000
  • 35
  • 244
  • 286
Kacy Raye
  • 1,312
  • 1
  • 11
  • 14

2 Answers2

1

In this instance I think it is just coincidence that the heap is already zeroed in the memory that is allocated.

You can read more in the answers to this similar question

Community
  • 1
  • 1
  • @JohnDibling Are you saying that `Student* heap = new Student;` will auto-initialise the members of Student? –  Jun 28 '13 at 13:04
  • I agree with John in saying it's not a coincidence, but I'm going to accept this answer because that link you provided gives a very thorough answer to my question so thank you! – Kacy Raye Jun 28 '13 at 13:08
  • @KacyRaye why don't you... upvote that answer instead? We can mark this a duplicate then. This will help future SO users. – sehe Jul 02 '13 at 10:37
0

Always initialize your variable to something meaningful. Else its allowed to take any values at random.

class Student {
public:
    int x;
Student(): x(0) {}
};
andre
  • 7,018
  • 4
  • 43
  • 75