When are Constructors Called in C++?

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 
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout 

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 
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout 

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 
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout 

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 
using namespace std;
class MyClass {
   public:
      MyClass() {
         cout 

Output

Inside Main
Declaring pointer
Calling Constructor
After creating dynamic object
Updated on: 2019-07-30T22:30:26+05:30

711 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements