c++ - error: passing const … as this argument of … discards qualifiers

c++ – error: passing const … as this argument of … discards qualifiers

c++ – error: passing const … as this argument of … discards qualifiers

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.

  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();

c++ – error: passing const … as this argument of … discards qualifiers

Related posts on c++ :

Leave a Reply

Your email address will not be published.