Calling non-const member function from const object without using this, why is it an error?

Viewed 62

Running the code below in g++ will result the following error:

error: passing 'const A' as 'this' argument discards qualifiers [-fpermissive]

struct A{
    void f(){};
};

int main(){
    const A a;
    a.f();
    return 0;
}

Where do we use this?

fpermissive implies that the code is non-conformant. Where does the standard states that this is an error?

1 Answers

The standard covers this in [class.this]. In particular, see example 2, where it says (in part):

The call y.g() is ill-formed because y is const and s​::​g() is a non-const member function.

When applied to your code, the equivalent statement is:

The call a.f() is ill-formed because a is const and A​::f() is a non-const member function.

To be clearer: A::f() is non-const because it lacks a const qualification; whether or not f() would be a legal const function (if the const qualification was added) is not relevant.

Perhaps what you are really interested in, though, is the first part of [class.this], where it states that the keyword this has a meaning in every non-static member function, regardless of whether or not this is ever used in that function.

Related