destructor

why is the destructor not called in the following program?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream.h> 
class IndiaBix
{
    int x; 
    public:
    IndiaBix(short ss)
    {
        cout<< "Short" << endl;
    }
    IndiaBix(int xx)
    {
        cout<< "Int" << endl;
    }
    IndiaBix(char ch)
    {
        cout<< "Char" << endl;
    }
    ~IndiaBix() 
    {
        cout<< "Final";
    }
};
int main()
{
    IndiaBix *ptr = new IndiaBix('B');
    return 0; 
}

Because you haven't destroyed the object with delete ptr;

You should always destroy anything you allocate once its no longer needed.
Heap allocated pointers don't call the destructor when they go out of scope. Here is a better way to write it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream> 
class IndiaBix
{
    int x; 
    public:
    IndiaBix(short ss)
    {
        cout<< "Short" << endl;
    }
    IndiaBix(int xx)
    {
        cout<< "Int" << endl;
    }
    IndiaBix(char ch)
    {
        cout<< "Char" << endl;
    }
    virtual ~IndiaBix() 
    {
        cout<< "Final";
    }
};
int main()
{
    shared_ptr<IndiaBix> ptr (new IndiaBix('B'));
    return 0; 
}


As you can see, I used a shared_ptr pointer so that the memory that was allocated on the heap is automatically destroyed. I also included a virtual destructor. You should always do this even if your class isn't inherited. Otherwise, it is considered very very bad practice. If your compiler doesn't yet support C++11 smart pointers, use auto_ptr or just delete manually. I think you are using an older compiler as you used #include <iostream.h> instead of #include <iostream> .
Last edited on
Topic archived. No new replies allowed.