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.
In the above code, semantically a temporary object of type
Ais getting created1, which is to be passed to the copy constructor ofA, 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
constin the definition as well::Now your code should compile.
1. Note that I said semantically a temporary object of type
Ais 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.