Error: passing 'const ...' as argument 'this' '...' discards qualifiers in the calling method
I am passing an object reference to a function, and I used const to indicate that this is a read-only method, but if I call another method inside that method, this error occurs even if I don't pass the reference as an argument.
error: passing 'const A' as argument 'this' of parameter 'void A :: hello ()' discards qualifiers [-fpermissive]
error: passing 'const A' as argument 'this' as argument '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;
}
source to share
Since sayhi()
const
, then all the functions that it calls must also be declared const
, in this case hello()
and world()
. Your compiler is warning you about const-correctness .
source to share