Search code examples
c++operator-overloading

How to overload copy assignment operator for const data members?


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_){};

Solution

  • you can use the const casting like so

    Station& operator=(const Station& station) { 
            const_cast<std::string> name_ = station.name_; // Work
            return *this;
        }