I was just experimenting with copy constructors and I got stuck by an odd output.
I wrote a program that uses classes as arrays (safe arrays).
Code:
#include <iostream>
#include <cstdlib>
using namespace std;

class array{
	int *p;
	int size;
public:
	array(int sz) {
		p = new int[sz];
		cout << "Using normal constructor" << endl;
		size = sz;
		if(!p) exit(1);
	}
	~array() { cout << "Destructing.. " << endl; delete [] p; }

	array(const array &a) {
		p = new int[a.size];

		for(int i=0; i<size; i++) p[i] = a.p[i];							
		size = a.size;
		cout << "Using copy constructor" << endl << endl;
	}
	int &getar(int x) {
		if(x<size && x>=0)	return p[x]; 
		else {
			cout << "Array size invalid : " << x << endl;
			exit(1);
		}
	}
};

int main()
{
	array x(10);
	for(int i=0; i<10; i++)	
		x.getar(i) = i*2;
	array y = x;
	cout << "array y's data : ";
	for(i=0; i<10; i++)
		cout << y.getar(i) << ' ';
	cout << endl << endl;	
	cout << "array x's data : ";
	for(i=0; i<10; i++)
		cout << x.getar(i) << ' ';
	cout << endl;
	return 0;
}
The output I get is very strange :
Code:
Using normal constructor
Using copy constructor

array y's data : -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451

array x's data : 0 2 4 6 8 10 12 14 16 18
Destructing..
Destructing..
I expected array y and array x to have the same data.. but the output shows a different result.. can somebody tell why this happens?