blue note
blue note

Reputation: 29089

explanation of "passing const XXX as this disregards qualifiers"?

I have the class

class Test {
public:
    void f() {}
    void g() const { f(); }
};

which fails to compile with

error: passing 'const Test' as 'this' argument discards qualifiers (in call to void Test::f())

I realise that I should not call non-const f from const g. However, I don't understand the content of the message. Where does the const Test object come from, and what qualifiers are discarded (f() does not have any qualifiers)??

Upvotes: 2

Views: 1030

Answers (2)

Bathsheba
Bathsheba

Reputation: 234785

It’s impossible1 to call f() from g() as g() is const (which means the implicit this pointer is const), and f() is not const.

Hence compilation fails with, in your case, a helpful diagnostic.


1 Well not quite impossible: A hack of which the behavior could be undefined if the object was created as const is

void g() const { const_cast<Test*>(this)->f(); }

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

The this pointer in a const member function is of type const Test*. That's how const-only member access is logically enforced. It's kind of an implementation detail, but a fairly reasonable one.

When you attempt to call f(), think of it as a hidden function argument being passed. The hidden function argument is the this pointer. f() is expecting a Test* but you're passing it a const Test*. A conversion between the two would "discard qualifiers", i.e. it would have to drop the const, which is not permitted.

The diagnostic is a little esoteric, I'll grant you, but it basically always means "you're trying to do a non-const thing in a const context".

Upvotes: 5

Related Questions