Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!!!

like image 617
Mathew Kurian Avatar asked Nov 12 '13 06:11

Mathew Kurian


2 Answers

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

like image 54
lolando Avatar answered Sep 17 '22 08:09

lolando


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" ;)

like image 34
Alex Jenter Avatar answered Sep 18 '22 08:09

Alex Jenter