virtual destructor doubt

Hi guys

please explain me the output of the below program....... any reply is appreciated

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
/* 
 
#include <iostream>
#include <string.h>
using namespace std;

class BB {
public:

    BB() {

        cout << "Base OK. ";

    }

    virtual ~BB() {

        cout << "Base DEL. ";

    }


};

class BD : public BB {
public:

    BD() {

        cout << "Derived OK. ";

    }

    ~BD() {

        cout << "Derived DEL. ";

    }

};

int main() {

    BB *b = new BD();
    delete b;
    return 0;

}

 */


Output:

Base OK Derived OK Derived DEL Base DEL

Last edited on
CLass constructorrs are called from most base to most derived. Destructors are called in backward order.
From my point of view, the output means that the constructor base is always called whenever an INSTANCE of its derived class is created, in this case, class BD. And of course, like nested loops, the last initiated class comes first(in this case, the derived class BD) and the first to be called comes last. In short, it does not follow the FIFO(First In First Out) rule. And oh, one more thing, constructor calls destructor(~classname) whenever it gets out of scope, or deleted(dynamically). I hope it helps. :)
if i modify the code and take our virtual from the first destructor the output is as follows

Base OK Derived OK Base DEL

as mentioned by the MiiniPaa
CLass constructorrs are called from most base to most derived. Destructors are called in backward order

then why its happening
if i modify the code and take our virtual from the first destructor the output is as follows

Base OK Derived OK Base DEL


If function (destructor in this case) is not virtual, it will be called based on type of pointer/reference and not on real type of object it contains. If your BD class adds some data, it will never be released, leading to incomplete destruction.
Yeah man you are right ........... i have checked it
thanks for your valuable information
Topic archived. No new replies allowed.