yayuj
yayuj

Reputation: 2464

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

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;
}

Upvotes: 3

Views: 2404

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

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.

Upvotes: 10

Related Questions