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
:
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.Clock::Clock()
is called to initailize Postoffice::clock
.Room::Room()
is called. Similar to 1. the member variables are called resulting in Clock::Clock()
running for Room::clock
.Room::Room()
runs. 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).Postoffice::Postoffice()
. At the end of the main
function p
goes out of scope resulting in:
Postoffice::~Postoffice()
runs.Postoffice
are destroyed in reverse order resulting so the body of Room::~Room()
running.Clock::~Clock()
is run for Room::clock
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.