Home > OS >  Why a constructor is called twice when an object is instantiated
Why a constructor is called twice when an object is instantiated

Time:10-01

Per my understanding, I know that when an object is instantiated, a constructor is called once. But I can't understand why both constructors are called and only one object is instantiated

#include <iostream>
using namespace std;
#define print(me) cout << me << endl;

class A 
{
    public:
    A() { print("default called"); }
    A(int x) { print("paramterized called"); }
};


int main()
{
    A a;
    a = A(10);
    return 0;
}

I got output: default called parameterized called

CodePudding user response:

In these lines

A a;
a = A(10);

there are created two objects of the type A. The first one is created in the declaration using the default constructor

A a;

And the second one is a temporary object created in the expression A( 10 )

a = A(10);

that then is assigned using the copy assignment operator to the already existent object a.

Due to the copy elision you could avoid the use of the default constructor by writing initially

A a = A( 10 );

In fact due to the copy elision it is equivalent to

A a( 10 );

provided that the copy constructor is not declared as explicit.

CodePudding user response:

You are also calling function while creating it with A a;

You can solve it by initializing value while creating it like this:

int main()
{
    A a = A(10); 
} 

Or as a Fareanor said :

 int main()
    {
        A a(10);
    } 

CodePudding user response:

According to me the constructor is called twice when an object is instantiated because as we know when we create an object we need to write class name with it, and also we know that the constructor has the same name that the class has. So it gets called twice.

  • Related