Order of Constructor and Destructor Calls in C++

This C++ program demonstrates the order of constructor and destructor calls for globally and locally initialized objects. The constructors of global objects are initialized earlier than local objects and the destructors for local objects are called earlier than global objects. Thus we can say that scope of a global object is larger than a local objects.

Here is the source code of the C++ program demonstrates the order of constructor and destructor calls for globally and locally initialized objects. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate order of constructor and destructor calls
  3.  */
  4. #include <iostream>
  5.  
  6. class A {
  7.     int i;
  8.     public:
  9.         A(int ii = 0) : i(ii)
  10.         {
  11.             std::cout << "A::A" << i << "() constructor "
  12.                       << std::endl;
  13.         }
  14.         ~A()
  15.         {
  16.             std::cout << "A::~A" << i << "() destructor "
  17.                       << std::endl;
  18.         }
  19. };
  20.  
  21. A a1(1);
  22.  
  23. int main()
  24. {
  25.     A a2(2);
  26. }

$ a.out
A::A1() constructor
A::A2() constructor
A::~A2() destructor
A::~A1() destructor

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.