Hi, I compile the following program using Microsoft Visual C++ 6.0:
Create.h
Create.cppCode:#ifndef CREATE_H #define CREATE_H class CreateAndDestroy { public: CreateAndDestroy(int, char *); ~CreateAndDestroy(); private: int object_id; char *message; }; #endif
TestCreate.cppCode:#include <iostream> #include "Create.h" using namespace std; CreateAndDestroy::CreateAndDestroy(int object_number, char *messageptr) { object_id = object_number; message = messageptr; cout << "Object " << object_id << " constructor runs " << message << endl; } CreateAndDestroy::~CreateAndDestroy() { if (object_id == 1 || object_id == 6) { cout << "\n"; } else { cout << ""; } cout << "Object " << object_id << " destructor runs " << message << endl; }
While the program is working, the result is not the one that I expect. Somehow, the destructor of object 1 is not getting called. I have debugged the program several time, but I cannot find the answer why destructor of object 1 is not getting called. Here is the result of the program:Code:#include <iostream> #include "Create.h" using namespace std; void create() { cout << endl << "CREATE FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy fifth(5, "(local automatic in create)"); static CreateAndDestroy sixth(6, "(local static in create)"); CreateAndDestroy seventh(7, "(local automatic in create)"); cout << endl << "CREATE FUNCTION: EXECUTION ENDS" << endl; } CreateAndDestroy first(1, "(global before main)"); int main() { cout << endl << "MAIN FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy second(2, "(local automatic in main)"); static CreateAndDestroy third(3, "(local static in main)"); create(); cout << endl << "MAIN FUNCTION: EXECUTION RESUMES" << endl; CreateAndDestroy fourth(4, "(local automatic in main)"); cout << endl << "MAIN FUNCTION: EXECUTION ENDS" << endl; return 0; }
Object 1 constructor runs (global before main)
MAIN FUNCTION: EXECUTION BEGINS
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)
Object 7 constructor runs (local automatic in create)
CREATE FUNCTION: EXECUTION ENDS
Object 7 destructor runs (local automatic in create)
Object 5 destructor runs (local automatic in create)
MAIN FUNCTION: EXECUTION RESUMES
Object 4 constructor runs (local automatic in main)
MAIN FUNCTION: EXECUTION ENDS
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)
Press any key to continue
Can you help me find the answer? Thank you for your help in advance.



LinkBack URL
About LinkBacks


