1

I am writing a code and this is a small part of a method i want to implement in a class that inherits from a base class:

const string & getType() const override {
    this->type = "Greedy";
    return type;
}

and this is the private part of the class:

private:

    const string type;
};

Also this is the method im overriding:

virtual const string & getType() const = 0;

when I try to compile the project i get the message:

passing (something) as 'this' argument discards qualifiers

I have seen similar questions but all of them did not have const in the class method that this message was appearing on. Here is a good example of one:

error: passing xxx as 'this' argument of xxx discards qualifiers

Where seems to be the problem?

Thanks

808kalli
  • 23
  • 7
  • 1
    Do you know what `const` does? If you read up on it your problem should become clear. Btw, why does this getter set something? That's a confusing implementation and you might want to overthink it. – Lukas-T Mar 18 '21 at 13:40
  • `this->type = "Greedy";` you can't modify the current object in a `const` function – drescherjm Mar 18 '21 at 13:54
  • 1
    `... getType() const` promises that the function will not modify `*this` as e.g. in `this->field = new_value`. You are doing exactly that. – chi Mar 18 '21 at 13:54
  • 1
    That wouldn't work even if you removed `const` from the function since the member variable is also `const`. You need to initialize the member variable when the object is created. (And note that const member variables are usually not what you want even when you think you do.) – molbdnilo Mar 18 '21 at 13:59
  • @chi thanks your comment really helped! – 808kalli Mar 18 '21 at 14:12
  • @molbdnilo thanks i totally understand! – 808kalli Mar 18 '21 at 14:14

1 Answers1

2

The first problem is that

const string type;

is a const member. That means, after it's initialization you can't assign any new value to it.

The second problem is, that the getter is also marked const:

//                       VVVVV
const string & getType() const override

Meaning you can't modiy member data from inside this function. Not to mention that it's a bad design if a getter changes a value before returning it.


If this override of getType is suppsed to always return "Greedy" you could do something like this:

const string & getType() const override {
    static std::string greedyType = "Greedy";
    return greedyType;
}
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • 1
    Thanks a lot i understand where the issue is. Essentially `const` getter promises that the members of the class wont be modified inside the method, as someone stated in the comments, so by me assinging the value "Greedy" to type i essentially change it. – 808kalli Mar 18 '21 at 14:09