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;
}
Since
sayhi()
isconst
, then all functions it calls must also be declaredconst
, in this casehello()
andworld()
. Your compiler is warning you about your const-correctness.