Mathew Kurian
Mathew Kurian

Reputation: 6039

Why is the destructor being called three times?

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 Constructor is only called twice!!!!

Upvotes: 5

Views: 2315

Answers (7)

Alex Jenter
Alex Jenter

Reputation: 4432

Because there are exactly 3 objects of class SimpleClass created, but your constructor is called only 2 times:

  • 1st object is a, calls your constructor;
  • 2nd is lol, which is initialized by copying from a via an implicitly defined copy constructor (thus bypassing your constructor);
  • 3rd is 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

user2915612
user2915612

Reputation: 1

Because destructor is the same for all objects.

Upvotes: 0

Santosh Sahu
Santosh Sahu

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

lolando
lolando

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

ldav1s
ldav1s

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

glglgl
glglgl

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

Jonathon Reinhart
Jonathon Reinhart

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

Related Questions