Destructor getting called twice? - Solution

Previous | Home

A good way of looking at this particular problem would be by remembering a simple rule,

Every call to the constructor must always, at some point, be followed by a call to the destructor.

In our program therefore when we assign '10' to 'm' which is of type "moo" the compiler simply adds instructions to create a temporary object of type "moo" (calling the constructor that takes the integer parameter) and simply assigns it to 'm'. In keeping with the above given rule, the compiler dutifuly arranges for the destructor to be called for the temporary once the assignment is made. This background activity would be immediately clear if we add one more line to the "main" function. The listing is given below.

void main()
{
	moo m;
	m = 10;
	cout<<"dooga booga"<<endl;
}

The output that this program produces is,

The Output

moo::moo()
moo::moo(int)
moo::~moo()
dooga booga
moo::~moo()

Here, the first call to the destructor is of'course for the temporary "moo" object and the second call for 'm' - the two calls being differentiated by the timely singing of the ancient tribal song of Bdoogledbub.

Previous | Home 1