I had trouble adding the foo
object into the map myFoos
until I found this answer which states that a default constructor is required.
When adding the object to the map, I was expecting it to be simply copied and put in place, however, what really happens is a default construction, an assignment and a copy.
Can someone explain this behaviour?
#include <map>
using namespace::std;
class Foo {
public:
Foo() { }; // Default
Foo(int id) : _id(id) { }; // Main
Foo(const Foo& other) { }; // Copy
Foo operator= (const Foo& other) { _id = other._id; return *this; } // Assign
int getID() { return _id; }
private:
int _id;
};
int main()
{
map<int,Foo> myFoos;
Foo foo(123); // Main
myFoos[123] = foo; // Default, Assign, Copy
}
Edit: I originally had no assignment happening in the function body of the assignment operator and some answers are correctly pointing that out. I modified the code accordingly.