0

I'm a little confused trying to understand what is happening here:

#include <iostream>

using namespace std;

class Point
{
  int x, y;
public:
  Point(): x(0), y(0) {}
  int getX() {return x;}
  int getY() {return y;}
};

int main(int argc, char const *argv[])
{
  Point *a = new Point[2];
  Point *b = a;

  for (int i = 0; i < 5; i++, a++)
    cout << a->getX() << "," << a->getY() << endl;

  delete[] b;

  return 0;
}

Output:

0,0
0,0
0,0
1041,0
825503793,667692

This is just an experiment, I looked at this when I was practicing with classes and dynamic memory. Why the output look like this, what is happening behind?

I'm sure than the 2 first Point will be initialized with the Point() constructor, so why the third is also 0,0? And why the other 2 have that random numbers, where are that objects allocated? Are there just random memory / uninitialized memory of Point type?

Biffen
  • 6,249
  • 6
  • 28
  • 36

0 Answers0