DawOp
DawOp

Reputation: 21

Why the copy constructor is called when I add a different object which is an argument in copy constructor?

I don't understand why the copy constructor is called while i am adding e to c.

struct A {};
struct B {
    B() { std :: cout << "B Constructor" << std :: endl; }
    B(const A&) { std :: cout << "B Copy" << std :: endl;}
    const B operator +(const B& arg);
};

const B B::operator +(const B& arg) {
    std :: cout << "+" << std :: endl;
    return B();
}

int main() {
    B c;
    A e;
    c + e;
}

Upvotes: 1

Views: 75

Answers (1)

lubgr
lubgr

Reputation: 38287

It's not the copy constructor being called, it's

B(const A&);

The copy constructor always has such a signature:

B(const B&);

As you haven't provided one, the compiler generates a copy constructor for you, but this one is indeed not called: you have an operator+ for B, which accepts a const B&, but the other operand is of type A. As the constructor mentioned first (B(const A&)) is implicit, this works out - a temporary B is instantiated from the A object named e, and the operator is invoked.

To make the output in your example more intuitive, consider changing the constructor B(const& A) to

B(const A&) { std::cout << "Construct B from A\n"; }

Upvotes: 3

Related Questions