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.
/*
* C++ Program to demonstrate order of constructor and destructor calls
*/
#include <iostream>
class A {
int i;
public:
A(int ii = 0) : i(ii)
{
std::cout << "A::A" << i << "() constructor "
<< std::endl;
}
~A()
{
std::cout << "A::~A" << i << "() destructor "
<< std::endl;
}
};
A a1(1);
int main()
{
A a2(2);
}
$ a.out A::A1() constructor A::A2() constructor A::~A2() destructor A::~A1() destructor
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy C++ Books
- Apply for Information Technology Internship
- Buy Computer Science Books
- Apply for C++ Internship
- Apply for Computer Science Internship