简体   繁体   中英

Why a constructor is called twice when an object is instantiated

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

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.

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);
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM