Mega Code Archive

 
Categories / C++ Tutorial / Class
 

Demonstrating the order in which constructors and destructors are called

#include <string> #include <iostream> using std::string; using std::cout; using std::endl; class MyClass  { public:    MyClass( int, string ); // constructor    ~MyClass();             // destructor private:    int objectID;    string message;  }; MyClass::MyClass( int ID, string s ) {    objectID = ID;    message = s;     cout << "Object " << objectID << " constructor runs " << message << endl; } MyClass::~MyClass() {     cout << "Object " << objectID << " destructor runs " << message << endl;  } void create( void ); MyClass first( 1, "(global before main)" ); int main() {    MyClass second( 2, "(local automatic in main)" );    static MyClass third( 3, "(local static in main)" );        create(); // call function to create objects    MyClass fourth( 4, "(local automatic in main)" );    return 0; } void create( void ) {    cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;    MyClass fifth( 5, "(local automatic in create)" );    static MyClass sixth( 6, "(local static in create)" );    cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl; } Object 1 constructor runs (global before main) Object 2 constructor runs (local automatic in main) Object 3 constructor runs (local static in main) CREATE FUNCTION: EXECUTION BEGINS Object 5 constructor runs (local automatic in create) Object 6 constructor runs (local static in create) CREATE FUNCTION: EXECUTION ENDS Object 5 destructor runs (local automatic in create) Object 4 constructor runs (local automatic in main) Object 4 destructor runs (local automatic in main) Object 2 destructor runs (local automatic in main) Object 6 destructor runs (local static in create) Object 3 destructor runs (local static in main) Object 1 destructor runs (global before main)