Here we will see, when constructors are called. Here constructors are of different types. Global, local, static local, dynamic.
For the global object, the constructors are called before entering into the main function.
Example
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
MyClass myObj; //Global object
int main() {
cout << "Inside Main";
}
Output
Calling Constructor
Inside Main
When the object is non-static, then, constructor is called when the execution reaches the point, where object is created.
Example
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
int main() {
cout << "Inside Main\n";
MyClass myObj; //Local object
cout << "After creating object";
}
Output
Inside Main
Calling Constructor
After creating object
When the object is local static, then only for the first time, its constructor will be called, if the same function is used again, it will not affect.
Example
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
void func() {
static MyClass myObj; //Local static object
}
int main() {
cout << "Inside Main\n";
func();
cout << "After creating object\n";
func();
cout << "After second time";
}
Output
Inside Main
Calling Constructor
After creating object
After second time
Finally for the dynamic object, the constructor will be called, when object is created using new operator.
Example
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
int main() {
cout << "Inside Main\n";
MyClass *ptr;
cout << "Declaring pointer\n";
ptr = new MyClass;
cout << "After creating dynamic object";
}
Output
Inside Main
Declaring pointer
Calling Constructor
After creating dynamic object