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]

3

3 Answers

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.

4
// **const object can call only const member function()** // **Modified Code** #include <bits/stdc++.h> using namespace std; class A { public: void hi() const { 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() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif A a; C c; c.receive(a); return 0; } 
1
  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(); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.