I get "Non const function is called on const object"
Of course. That's the whole point of const
in the first place!
if (name.size() > 20)
{
name.reserve(20);
}
This does not make sense at all. It literally says: "If the string has more than 20 characters, then make sure that it can internally hold at least 20 characters".
Now, the call may also have the effect that the string's internal capacity shrinks to whatever size greater than 20 it represents to the outside world. For example, if your string has size 30 and its current capacity is 1000, then reserve(20)
may shrink the capacity to 30.
However, this is a low-level memory-management concern a beginner typically doesn't or shouldn't care about. If, what I believe, your intention is merely to cut the string, then you need resize
.
I would solve your problem like this, plain and simple:
void setName(std::string const& name)
{
this->name = name;
if (this->name.size() > 20)
{
this->name.resize(20);
}
}