StarPinkER
StarPinkER

Reputation: 14281

g++ cannot find the correct copy constructor when doing copy initialization

With the following code:

class B{};
class A{
public: 
    A(B& b);
    A(const A& a);  
};
A::A(B& b){
}
A::A(A& a){
}
int main(){
    B b;
    A a = b;
}

no matching function call to 'A::A(A)'

I looked up some references, and thought it might caused by the Return Value Optimization (RVO), so I tried to disable the optimization by the -fno-elide-constructor option. Problem still remains.

Upvotes: 0

Views: 106

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361812

A a = b;

In the above code, semantically a temporary object of type A is getting created1, which is to be passed to the copy constructor of A, but as you've defined the copy-constructor, it takes the argument by non-const reference, but the temporary object cannot be bound to the non-const reference, hence the error.

So what you need to do is to add const in the definition as well::

A::A(A const &a)   //const added
{
} 

Now your code should compile.

1. Note that I said semantically a temporary object of type A is getting created. The compiler might optimize this step (in fact, any decent compiler will optimize this step) and the temporary object may be created in actuality and the copy-constructor may be actually called. But even if it is not actually getting called, you need accessible copy-constructor for semantic check only.

Upvotes: 1

Related Questions