I was trying a move constructor example as shown below:
#include <iostream>
#include <string.h>
using namespace std;
class Class1
{
string name;
public:
//Parameterized ctor
Class1(string nm): name(nm)
{
cout <<"\nClass1 Parameterized Constructor" << endl;
}
//move ctor
Class1(string&& other): name(std::move(other))
{
cout <<"\nClass1 Move Constructor" << endl;
}
};
class Class2
{
Class1 class1_obj;
public:
//Parameterized ctor
Class2(Class1 param): class1_obj(param)
{
cout <<"\nClass2 Parameterized Constructor" << endl;
}
//move ctor
Class2(Class1&& param): class1_obj(std::move(param))
{
cout <<"\nClass2 Move Constructor" << endl;
}
};
int main()
{
string obj7("Suraj");
Class1 obj6(obj7);
Class2 obj5(move(obj6));
return 0;
}
Compiler is generating following error:
error: call of overloaded 'Class2(std::remove_reference<Class1&>::type)' is ambiguous Class2 obj5(move(obj6));
I changed the Class2 parameterized ctor by adding a reference to the parameter in the definition as:
Class2(Class1& param): class1_obj(param)
{
cout <<"\nClass2 Parameterized Constructor" << endl;
}
What is the reason for this error? Is the solution correct, and if yes, what should be done to declare the same ctor without a reference?