Tejaswi Burgula
Tejaswi Burgula

Reputation: 339

Why copy constructor was called twice in following program?

Why copy constructor is being called twice in below program. Is this correct behaviour? If i dont use initializer list, Its calling Default constructor of A.

class A
{
    public:
    A(){cout<<"A()\n";}
    A(const A &a){cout<<"A(A)\n";}
};
class B
{
    private:
    A aa;
    public:
    B(A bb):aa(bb)
    { 
        cout<<"B(A)\n";
    }
};
int main(int argc,char** argv)
{
    A cc;
    B b(cc);
}

Output:

A()
A(A)
A(A)
B(A)

Upvotes: 1

Views: 70

Answers (1)

cadaniluk
cadaniluk

Reputation: 15229

The first time it is called when cc is passed to the constructor B::B(A) of B.

The second time it is called when b.aa is initialized with bb in the member initializer list of the constructor B::B(A).

Upvotes: 4

Related Questions