简体   繁体   中英

can anyone explain how this programm runs in sequence?

I dont understand how the room and clock constructors are called

when we call postoffice constructor and what will be the order of constructors and destructors.

#include <iostream>

using namespace std;

class Clock{
    int HH, MM;
public :
    Clock():HH(0), MM(0){
        cout<<"Constructor Clock "<<endl;
    }
    Clock(int hh,int mm): HH(hh), MM(mm){
        cout<<"constructor clock at "<<hh<<mm<<endl;
    }
    ~Clock(){
        cout<<"Destructor Clock"<<endl;
    }
};

class Room{
    Clock clock;
public:
    Room(){
        cout<<"Constructor room"<<endl;
    }
    ~Room(){
        cout<<"Destructor room"<<endl;
    }
};

class Postoffice{
    Clock clock;
    Room room;
public:
    Postoffice(){
        clock=Clock(18,30);
        cout<<"Constructor postoffice"<<endl;
    }
    ~Postoffice(){
        cout<<"Destructor postoffice"<<endl;
    }
};

int main(){
    Postoffice p;
    return 0;
}

Here's the sequence of events during initialization of p :

  1. Postoffice::Postoffice() is called. Before the body of the function is entered, the initializers of all members of Postoffice run in the order of declaration.
  2. Clock::Clock() is called to initailize Postoffice::clock .
  3. Room::Room() is called. Similar to 1. the member variables are called resulting in Clock::Clock() running for Room::clock .
  4. The body of Room::Room() runs.
  5. The body of Postoffice::Postoffice() runs and clock=Clock(18,30); is executed. This first creates a temporary Clock object that is move assigned to the Postoffice::clock . At the end of this expression the temporary Clock object gets destroyed ( Clock::~Clock() call).
  6. Print from Postoffice::Postoffice() .

At the end of the main function p goes out of scope resulting in:

  1. The destructor body Postoffice::~Postoffice() runs.
  2. After the completion of the destructor body the member variables of Postoffice are destroyed in reverse order resulting so the body of Room::~Room() running.
  3. After the body completes, the destructor Clock::~Clock() is run for Room::clock
  4. With the destruction of Postoffice::room completed Postoffice::clock gets destroyed running Clock::~Clock() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM