The following program works without error.
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
class userContext {
public:
int id;
int value1;
int value2;
userContext():id(-1),value1(-1),value2(-1){}
userContext(userContext &context) {
this->id = context.id;
this->value1 = context.value1;
this->value2 = context.value2;
}
};
int main() {
userContext a;
a.id = 1;
a.value1 = 2;
a.value2 = 3;
// map<int,userContext> Map;
// Map[1] = a;
cout << a.value1 << endl;
cout << a.value2 << endl;
return 0;
}
But If I introduce a map, it gives an error. Why is it so?
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
class userContext {
public:
int id;
int value1;
int value2;
userContext():id(-1),value1(-1),value2(-1){}
userContext(userContext &context) {
this->id = context.id;
this->value1 = context.value1;
this->value2 = context.value2;
}
};
int main() {
userContext a;
a.id = 1;
a.value1 = 2;
a.value2 = 3;
map<int,userContext> Map;
Map[1] = a;
cout << Map[1].value1 << endl;
cout << Map[1].value2 << endl;
return 0;
}
part of compilation error output:
locks.cpp:20:7: required from here
/usr/include/c++/7/bits/stl_pair.h:292:17: error: ‘constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int; _T2 = userContext]’ declared to take const reference, but implicit declaration would take non-const
constexpr pair(const pair&) = default;
However, changing copy constructor signature to userContext(const userContext &context)
resolves the compilation error and programs executes fine. Please explain.
Thanks!