I have a class: class1
with a private member variable:
std::unordered_map<std::string, class2> s_list;
I am trying to insert or assign objects of class2
in the above s_list
.
The class2
has a copy constructor of the form:
class2::class2(const class2& obj)
{
x = obj.x;
y = obj.y;
}
It also has another constructor:
class2::class2(std::string x1, double y1)
{
x = x1;
y = y1;
}
Inside one of the functions of class1
, I have the following lines:
class2 s_obj(x1, y1);
s_list[x1] = s_obj;
However, it throws the error:
error: no matching function for call to ‘class2::class2()’
second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
^
What am I missing here?
You are missing a default ctor
. In an unordered_map
if there is no match for a value of a key
it creates a default one and returns a reference to it.
Consider the subscript operator []
.See Here. Closely observe the return T&
If you do s_list["foo"]
and there is no value
associated with "foo" it creates a entry in the unordered_map with key
"foo" and returns a reference to the default value by callings its default ctor.
In your class2 you dont have one. To fix it create a default ctor
class class2 // horrible name btw
{
class2() = default;
}
or use insert
. Reference