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

C++

C++ Problem Overview


> 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]

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

  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); > ref.hi();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyayujView Question on Stackoverflow
Solution 1 - C++therealrootuserView Answer on Stackoverflow
Solution 2 - C++monkView Answer on Stackoverflow