Input:
#include <iostream>
using namespace std;
class SimpleClass
{
public:
SimpleClass()
{
cout<<"SimpleClass Constructor\n";
}
virtual ~SimpleClass()
{
cout<<"SimpleClass destructor\n";
}
};
int main()
{
SimpleClass a;
SimpleClass lol = a;
SimpleClass b;
SimpleClass * lol2 = &b;
}
Output:
SimpleClass Constructor
SimpleClass Constructor
SimpleClass destructor
SimpleClass destructor
SimpleClass destructor
I am confused why the destructor is being called 3 times.
The destructor is being called three times, for a
, lol
and b
.
In your case, a
and b
are instantiated using the default constructor
. However note that lol
is instantiated using the copy constructor
Because there are exactly 3 objects of class SimpleClass created, but your constructor is called only 2 times:
a
, calls your constructor; lol
, which is initialized by copying from a via an implicitly defined copy constructor (thus bypassing your constructor);b
, calls your constructor.Note that lol2
is just a pointer to b, so no extra calls are made.
And the correct name is "destructor", not "deconstructor" ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With