Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to demonstrate the order of call of constructor and destructor . Create objects in different scopes.

C++ Code Example — Constructor Programs

ADVERTISEMENT

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

  1. Create a class Test that takes a string in its constructor and prints it so you know which object was created.
  2. Include a destructor that prints "Destructor called".
  3. Instantiate a Global object (outside of main).
  4. Instantiate Local objects inside main.
  5. Call a class function that instantiates another Local object inside a smaller function scope.
  6. 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)
ADVERTISEMENT