Search code examples
c++objectruntimeheap-memoryinstance-variables

Why do instance variables of run-time stack objects differ from heap objects?


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?


Solution

  • 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