2

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_){};
5
  • 2
    maybe remove the const from the name declaration const 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. Commented Mar 7, 2021 at 13:05
  • 4
    "I have a class like this and need to build a copy assignment operator where the name_ must be const" - One of those requirements has to be dropped - unless you make a copy constructor/assignment operator that copies everything but name_. Commented Mar 7, 2021 at 13:08
  • 3
    From a design perspective, you don't. Having a const member 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 an operator=() for a class with a const member you must (1) justify such a broken design (2) implement the operator=() so it assigns other members, but not the const ones. Commented Mar 7, 2021 at 13:57
  • @TedLyngmo Presumably the copy constructor should copy 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. Commented Mar 7, 2021 at 14:03
  • Thanks @Peter ! for the clarification. Yes I can understand I was wrong from design perspective. Commented Mar 7, 2021 at 16:31

1 Answer 1

0

you can use the const casting like so

Station& operator=(const Station& station) { 
        const_cast<std::string> name_ = station.name_; // Work
        return *this;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.