Destructor getting called twice?

Previous | Next | Home

What follows is a little C++ program. The output that it produces is given after the listing. What you need to figure out is exactly how the destructor gets called twice.

The Program

#include <iostream>
using namespace std;

class moo
{
public:
	moo()
	{
		cout<<"moo::moo()\n";
	}

	moo(int i)
	{
		cout<<"moo::moo(int)\n";
	}

	~moo()
	{
		cout<<"moo::~moo()\n";
	}
};

void main()
{
	moo m;
	m = 10;
}

The Output

moo::moo()
moo::moo(int)
moo::~moo()
moo::~moo()

Now it is understandable that the second constructor, i.e., the constructor that takes an integer argument is getting called here (as is evident from the second line of the output) since there is a conversion that needs to take place. But what is inexplicable is the reason why the destructor is being called twice instead of once! Is it being called on the same object (which of'course is a most dangerous prospect)?

If you can figure it out and have something to say to me about it do write to me at acheeriunni@yahoo.com. Otherwise if you'd like to know the answer right now just click here.

See ya ;-)

Previous | Next | Home 1