When are the constructors called for different types of objects like global, local, static local, dynamic?
1) Global objects: For a global object, constructor is called before main() is called. For example, see the following program and output:
#include using namespace std; class Test { public : Test(); }; Test::Test() { cout << "Constructor Called \n" ; } Test t1; int main() { cout << "main() started\n" ; return 0; } /* OUTPUT: Constructor Called main() started */ |
2) Function or Block Scope ( automatic variables and constants ) For a non-static local object, constructor is called when execution reaches point where object is declared. For example, see the following program and output:
using namespace std; class Test { public : Test(); }; Test::Test() { cout << "Constructor Called \n" ; } void fun() { Test t1; } int main() { cout << "Before fun() called\n" ; fun(); cout << "After fun() called\n" ; return 0; } /* OUTPUT: Before fun() called Constructor Called After fun() called */ |
For a local static object, the first time (and only the first time) execution reaches point where object is declared. For example, output of the following program is:
#include using namespace std; class Test { public : Test(); }; Test::Test() { cout << "Constructor Called \n" ; } void fun() { static Test t1; } int main() { cout << "Before fun() called\n" ; fun(); cout << "After fun() called\n" ; fun(); //constructor is not called this time. return 0; } /* OUTPUT Before fun() called Constructor Called After fun() called */ |
3) Class Scope: When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructurs or constructor without parameter then these constrctors are called automatically, otherwise parameterized constructors can be called using Initializer List. For example, see PROGRAM 1 and PROGRAM 2 and their output.
No comments:
Post a Comment