There is a rule known as the "rule of 3". It says that if you need to write a copy constructor, assignment operator, or destructor.... you likely need to write all 3 of them.
In your case... when your Foo object is being copied, you are just copying the pointer. So what's happening is that 'a' in main is being copied to 'f' in print.
So a.ptr and f.ptr now point to the same memory.
When 'f' is destroyed, it will delete f.ptr (which also deletes a.ptr since they point to the same memory)
Then, when 'a' is destroyed, it attempts to delete that
again resulting in the crash.
So fix, you need to write a copy constructor which will reallocate this buffer for the new object and do a deep copy:
1 2 3 4 5 6 7 8
|
Foo::Foo(const Foo& obj) // copy constructor
{
// create a new buffer and copy over its contents
N = obj.N;
ptr = new int[N];
for ( int c = 0 ; c < N ; c++ )
ptr[c] = obj.ptr[c];
}
|
You'll also need to write an assignment operator, or else you'll have the same issue when you try to assign objects.
Of course... none of this is an issue if you use smart pointers instead of manual memory management. My general rule is that if you are manually deleting... you're doing it wrong.
EDIT: ninja'd!