简体   繁体   中英

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

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

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