ERROR MSG:
error: passing 'const string {aka const std::__cxx11::basic_string<char>}' as 'this' argument discards qualifiers [-fpermissive]
I have a class like this and need to build a copy assignment operator where the name_ must be const.
How to overcome the error?
class Station
{
private:
const string name_;
Station& operator=(const Station& station) {
name_ = station.name_; //ERROR
return *this;
}
public:
Station(string name):
name_(name){};
Station(const Station& station): name_(station.name_){};
constfrom the name declarationconst string name_. It may be that when you try to assign station.name to it you violate your own rule of this member to be constant.name_must be const" - One of those requirements has to be dropped - unless you make a copy constructor/assignment operator that copies everything butname_.constmember means that it is not possible to assign that member after it is initialised. But the purpose of an assignment operator is generally to assign all members of the class after they have been initialised. If you must supply anoperator=()for a class with aconstmember you must (1) justify such a broken design (2) implement theoperator=()so it assigns other members, but not theconstones.name_, since its only other choice would be to make it empty. But if the class does that, it will violate the Principle of Least Surprise.