Reputation: 17
This is a program from a past paper in an upcoming exam. I've tried editing the file a bit to see what happens, but I'm still confused as to why it prints in this particular order.
#include <iostream>
using namespace std;
class HAMMER
{
public:
HAMMER() {cout << " HAMMER";}
virtual ~HAMMER() { cout << " ~HAMMER "; }
};
class TAPE
{
public:
TAPE(){cout << " TAPE "; }
virtual ~TAPE() { cout << " ~TAPE"; }
};
class TOOL
{
public:
TOOL(){cout << " TOOL "; }
virtual ~TOOL() { cout << " ~TOOL"; }
protected:
HAMMER hammer;
};
class WRENCH
{
public:
WRENCH(){cout << " WRENCH "; }
virtual ~WRENCH() { cout << " ~WRENCH"; }
protected:
HAMMER hammer;
};
class SHOVEL
{
public:
SHOVEL(){cout << " SHOVEL "; }
virtual ~SHOVEL() { cout << " ~SHOVEL"; }
protected:
TAPE dog;
};
class SWEEPER: public TOOL
{
public:
SWEEPER(){cout << " SWEEPER "; };
virtual ~SWEEPER(){ cout << " ~SWEEPER " ; };
protected:
TAPE dog;
WRENCH wrench;
SHOVEL shovel;
};
int main()
{
SWEEPER b;
}
This is the output
HAMMER TOOL TAPE HAMMER WRENCH TAPE SHOVEL SWEEPER ~SWEEPER ~SHOVEL ~TAPE ~WRENCH ~HAMMER ~TAPE ~TOOL ~HAMMER
Why is TAPE not appearing before TOOL? And similarly not appearing second in the reverse?
Edit: It seems other than those two it appears exactly in order from top to bottom, then again in reverse
Upvotes: 0
Views: 81
Reputation: 10185
This is the order of construction:
During destruction, objects are destroyed in the reverse order. But in this case, destructor body is executed before destroying the members.
Upvotes: 2