// This code demonstrates order of constructors and destuctors. // // The order of construction for class Foo is: // // • Foo’s base class is constructed // • Foo’s member variables are constructed, in order of declaration // • Foo’s ctor is called // // Foo’s member variables MUST be constructed before Foo’s constructor // is called. What other choice do we have? AFTER Foo’s ctor? // That would wipe out any values that we put into those variables. // // Destructors occur in reverse order of constructors: // // • Foo’s dtor is called // • Foo’s member variables are destroyed, in reverse order of declaration // • Foo’s base class is destroyed // // In a function, ctors are called in declaration order. // Dtors are called in the opposite order. // // It also shows that initialization list order is checked by g++ -Wall. #include using namespace std; class Alpha { public: Alpha(int n) { clog << __PRETTY_FUNCTION__ << " n=" << n << '\n'; } ~Alpha() { clog << __PRETTY_FUNCTION__ << '\n'; } }; class Beta { public: Beta(int n) { clog << __PRETTY_FUNCTION__ << " n=" << n << '\n'; } ~Beta() { clog << __PRETTY_FUNCTION__ << '\n'; } }; class Gamma { public: Gamma(int n) { clog << __PRETTY_FUNCTION__ << " n=" << n << '\n'; } ~Gamma() { clog << __PRETTY_FUNCTION__ << '\n'; } }; class Delta : public Gamma { public: Delta() : b(12), Gamma(14), a(13) { clog << __PRETTY_FUNCTION__ << '\n'; }; ~Delta() { clog << __PRETTY_FUNCTION__ << '\n'; } private: Alpha a; Beta b; }; int main() { Delta d; }