Reputation: 6039
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.
Upvotes: 5
Views: 2315
Reputation: 4432
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" ;)
Upvotes: 6
Reputation: 2244
SimpleClass lol = a; //calls the default copy constructor which you have not defined
Override the copy constructor then you might see one new constructor called.
Upvotes: 2
Reputation: 1751
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
Upvotes: 11
Reputation: 16315
You've got 3 objects a
, lol
, and b
. You aren't tracking a copy constructor which is generated by the compiler (this one is called by lol
), so that's why there's only two constructors.
Upvotes: 5
Reputation: 91149
You have a
, lol
and b
.
Maybe you could print their addresses in main()
and as well in the constructor and destructor, then you'll see it.
Upvotes: 0
Reputation: 137547
It's being called once each for a
, lol
, and b
.
To confirm this, you could add a field to the class, and assign each of them a name/id, which you print out in the destructor. You could also print out the value of this
, which is a pointer to the object.
Upvotes: 3