Extra destructor in c++?
In your c++ class sometime, you might have faced this dilemma. You create some objects. Your class has constructors and destructor (no pluarl here). And each of these methods displays message. And your output shows one extra destructor that is to say if there are 3 constructor calls then four destructor calls will be shown. What is the problem here.?
We have a very simple class with 2 constructors and a destructor. We also a global method which has Number object as parameter. Now here is the output of the program
We are seeing 2 constructors and 3 destructors.
The extra destructor is coming from the object created within square function using copy constructor which was provided by the compiler.. As the parameter num is value parameter, it calls copy constructor and this copied object is destroyed when this function is returned. Hence the extra destructor.
Now let us write our own copy constructor and observe the output
And the output is
We have a very simple class with 2 constructors and a destructor. We also a global method which has Number object as parameter. Now here is the output of the program
The extra destructor is coming from the object created within square function using copy constructor which was provided by the compiler.. As the parameter num is value parameter, it calls copy constructor and this copied object is destroyed when this function is returned. Hence the extra destructor.
Now let us write our own copy constructor and observe the output
Number(Number &other)
{
n = other.n;
cout<<"copy constructor\n";
}
And the output is
Comments
Post a Comment