I think the question is pretty simple and it can be shrunk in few words such "which operator does the compiler overload automatically?" I've got an idea about what is going on but I'm currently missing some details able to explain me why it's working as it's.
Unfortunately I did not find anything of useful into my Stroustrup's C++ reference and I'm pretty sure that somebody of you can help me figuring out what's happening. Let's open the discussion: here's a little snapshot something similar to the code I was looking at:
class MyPair : public pair<string,string>
{
public:
MyPair()
{
pair<string,string>();
}
};
So far nothing of strange, as widely discussed in the thread What are all the member-functions created by compiler for a class? Does that happen all the time? the compiler will automatically generate a default version of copy constructor a copy assignment operator and a destructor but not a default constructor just because I redefined my own. Thanks to the compiler I'll be able to assign a new object at the creation time using the default copy constructor and to use the assignment operator just after the creation of an object, as showed here:
//default copy constructor
MyPair mypair1 = mypair;
MyPair mypair2;
//default assignment operator
mypair2 = mypair1
Until now, everything works as designed. Imagine now that I would like, for some unknown reason, to assign a string object to MyPair object, like it follows:
int main()
{
pair<string,string> aPair;
MyPair mypair;
string mystring("test");
//ERROR
mypair = mystring;
return 0;
}
Before I tested out this line of code, I was expecting that the compiler would have complained about (because I didn't provide to it any explicit overload of the operator=, so by itself is not able to assign a string to the created object), and indeed it returned me a quite self-explicative error, like:
test.cpp:36:13: error: no match for ‘operator=’ in ‘mypair = mystring’
test.cpp:36:13: note: candidate is:
test.cpp:7:7: note: MyPair& MyPair::operator=(const MyPair&)
Now, imagine to complete the MyPair class by adding the following method:
MyPair(const string& astring)
{
pair<string,string>(astring,string());
}
Suddenly, the code starts compiling, without giving anymore any kind of error. To my eyes it seems that the above method provided to the compiler some kind of cleverness; it started generating the missing MyPair& MyPair::operator=(const string &s).
I have to admit that it sounds really brilliant, but I cannot understand exactly why it happens. Would it mean that for each additional constructor I put in place into MyPair the coplier will generate an additional overloaded operator= that makes my class being copy assignable to the specified reference just because of that?