WAP to demonstrate the order of call of constructor and destructor . Create objects in different scopes.
Objective
Write a C++ program to demonstrate the exact execution order of Constructors and Destructors across different scopes.
Algorithm / Approach
- Create a
class Testthat takes astringin its constructor and prints it so you know which object was created. - Include a destructor that prints "Destructor called".
- Instantiate a Global object (outside of
main). - Instantiate Local objects inside
main. - Call a class function that instantiates another Local object inside a smaller function scope.
- Observe the order of the print statements.
main.cpp
#include<iostream>
using namespace std;
class Test {
public:
Test(string a){
cout<< a<<" constructor invoked\n";
}
void show() {
Test t("in function");
}
~Test() {
cout<<"Distructor called"<< endl;
}
};
Test t3("Before Main");
int main() {
Test t1("in main");
t1.show();
Test t2("After function call");
return 0;
}
Expected Output
Before Main constructor invoked in main constructor invoked in function constructor invoked Distructor called After function call constructor invoked Distructor called Distructor called Distructor called
Explanation of the Program
- This is a crucial concept in C++ memory management. Global objects are constructed BEFORE
main()even begins. - Local objects are constructed the moment their line of code is executed. They are destroyed in REVERSE order of their creation the exact moment they go out of scope (e.g., when the function they were created inside finishes running).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)