kdhug886 kdhug886 -4 years ago 69
C++ Question

The order of destructor

#include <iostream>
#include <cstring>
using namespace std;

class Ghost{
public:
Ghost(){
strcpy(name, "");
cout << "Ghost(" << name <<")" <<endl;
}

Ghost(char n[]){
strcpy(name, n);
cout << "Ghost(" << name << ")" << endl;
}
~Ghost(){
cout <<"~Ghost(" << name << ")" << endl;
}

private:
char name[20];
};

class PacMan{
public:
PacMan(){
inky = new Ghost("Inky");
pinky = NULL;
cout << "PacMan()" << endl;
}

PacMan(Ghost* other){
inky = NULL;
pinky = other;
cout << "PacMan(other)" << endl;
}

~PacMan(){
if (inky!= NULL)
delete inky;
cout <<"~PacMan()" << endl;
}

private:
Ghost blinky;
Ghost *inky;
Ghost *pinky;
};

int main(){
PacMan pm1;
Ghost* other = new Ghost("other");
PacMan* pm2 = new PacMan(other);

delete pm2;
delete other;

return 0;
}


For this program, it output:

Ghost()
Ghost(Inky)
PacMan()
Ghost(other)
Ghost()
PacMan(other)
~PacMan()
~Ghost()
~Ghost(other)
~Ghost(Inky)
~PacMan()
~Ghost()


I wanted to know where the first output Ghost() come from, and why the last three output wasn't

~PacMan()
~Ghost(Inky)
~Ghost()


I think the order of destructor is the opposite of the constructor order, is it true?

Answer Source

The first Ghost is the PacMan member blinky.

About the last order: Destroying pm1 exectutes

~PacMan(){
        if (inky!= NULL)
            delete inky;
        cout <<"~PacMan()" << endl;
    }  

and then blinky is deleted too.
If you want the opposite order, you've to write it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download