Why Not Destructor is Calling

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
using namespace std;

class A{
      int i;
      int b;
      public:
             A(){
                   i=0;
                   b=0;
                   cout<<"constructor"<<endl;
                 }
             int printf(){
                      cout<<i<<" "<<b<<endl;
                      return 1;
                      } 
                      
             ~A(){
                  cout<<"A out of scope"<<endl;
                  }            
      };
class B:public A {
      int i;
      int b;
      public:
             B(){
                 i=0;
                 b=9;
                 cout<<"constructor of B"<<endl;
                 }
             int printf(){
                      cout<<i<<" "<<b<<endl;
                      return 1;
                      } 
             ~B(){
                  cout<<"B out of scope"<<endl;
                  }    
      };      

int main(){
    A obj;
    obj.printf();
    B obj1;
    obj1.printf();
    
    
    
    
    cout<<endl;
    
    
    system("pause");
    return 0;
    }
I've reduced your code to this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;

class A{
public:
    A() { cout<<"constructor of A"<<endl; }
    ~A(){ cout<<"destructor of A"<<endl;  }            
};
class B:public A {
public:
    B() { cout<<"constructor of B"<<endl; }
    ~B(){ cout<<"destructor of B"<<endl;  }    
};      

int main()
{
    A objA;
    B objB;
}
constructor of A
constructor of A
constructor of B
destructor of B
destructor of A
destructor of A


These destructors are being called. You have system("pause"); in there. The destructors are only called AFTER system("pause");

Try running your console app in the console instead of double-clicking on the ICON like so:
Microsoft Windows [Version 6.2.8250]
(c) 2012 Microsoft Corporation. All rights reserved.

C:\Users\Stew>cd "C:\Dev\Snippets\Release"
C:\Dev\Snippets\Release>Snippets.exe
constructor of A
constructor of A
constructor of B
destructor of B
destructor of A
destructor of A

C:\Dev\Snippets\Release>
Last edited on
Or change main to limit the scope of the objects:
1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){
    {
        A obj;
        obj.printf();
        B obj1;
        obj1.printf();
   
        cout<<endl;
    } 
    
    system("pause");
    return 0;
}
Topic archived. No new replies allowed.