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.
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]Related Posts:
- Check Programming Books
- Check C++ Books
- Practice Programming MCQs
- Check Computer Science Books
- Practice Computer Science MCQs