Seán
Seán

Reputation: 17

Don't understand the output of this program

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

Answers (1)

VLL
VLL

Reputation: 10185

This is the order of construction:

  • Sweeper constructor begins
  • Sweeper has parent class Tool -> Tool constructor begins
    • Tool has hammer member -> prints HAMMER
    • Tool constructor finishes -> prints TOOL
  • Sweeper members are constructed in the same order as written: Tape, wrench, shovel
    • Tape constructor -> prints TAPE
    • Wrench constructor begins
      • Wrench has hammer member -> prints HAMMER
      • Wrench constructor finishes -> prints WRENCH
    • Shovel constructor begins
      • Shovel has hammer member -> prints HAMMER
      • Shovel constructor finishes -> prints SHOVEL
  • Sweeper constructor finishes -> prints SWEEPER

During destruction, objects are destroyed in the reverse order. But in this case, destructor body is executed before destroying the members.

Upvotes: 2

Related Questions