error: passing 'const …' as 'this' argument of '…' discards qualifiers in calling method

2.3k views Asked by At

I'm passing the reference of an object to a function and I used const to indicate that it's read-only method, but if I call another method inside of that method this error occur, even if I'm not passing the reference as argument.

error: passing 'const A' as 'this' argument of 'void A::hello()' discards qualifiers [-fpermissive]

error: passing 'const A' as 'this' argument of 'void A::world()' discards qualifiers [-fpermissive]

#include <iostream>

class A
{
public:
    void sayhi() const
    {
        hello();
        world();
    }

    void hello()
    {
        std::cout << "world" << std::endl;
    }

    void world()
    {
        std::cout << "world" << std::endl;
    }
};

class B
{
public:
    void receive(const A& a) {
        a.sayhi();
    }
};

class C
{
public:
    void receive(const A& a) {
        B b;
        b.receive(a);
    }
};

int main(int argc, char ** argv)
{
    A a;
    C c;
    c.receive(a);

    return 0;
}
1

There are 1 answers

3
Cory Kramer On BEST ANSWER

Since sayhi() is const, then all functions it calls must also be declared const, in this case hello() and world(). Your compiler is warning you about your const-correctness.