54
votes

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

I don't understand why I'm getting this error, I'm not returning anything just passing the reference of the object and that is it.

#include <iostream>

class A
{
public:
    void hi()
    {
        std::cout << "hi." << std::endl;
    }
};

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

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

@edit

I fixed it using const correctness but now I'm trying to call methods inside of the same method and I get the same error, but the weird thing is that I'm not passing the reference to this method.

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

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]

2
hi is a non-const member function; a is const.Oliver Charlesworth
passing means as an (implicit) argument. Does not have anything to do with returning.Deduplicator

2 Answers

54
votes

Your hi method is not declared as const inside your A class. Hence, the compiler cannot guarantee that calling a.hi() will not change your constant reference to a, thus it raises an error.

You can read more about constant member functions here and correct usage of the const keyword here.

0
votes
  1. As already mentioned, one option is to make hi method const-qualified.

  2. Another option is to use const_cast at the time of calling the hi method like so

A& ref = const_cast <A&>(a);
ref.hi();