G ++: const discards qualifiers

why am I getting discard qualifiers error:

 customExc.cpp: In member function 'virtual const char* CustomException::what() const': customExc.cpp: error: passing 'const CustomException' as 'this' argument of 'char customException::code()' discards qualifiers 

in the following code example

 #include <iostream> class CustomException: public std::exception { public: virtual const char* what() const throw() { static std::string msg; msg = "Error: "; msg += code(); // <---------- this is the line with the compile error return msg.c_str(); } char code() { return 'F'; } }; 

I searched around SOF before considering simulation issues.

I have already added const to all possible places.

Please enlighten me - I do not understand ...

EDIT : here are the steps to play on Ubuntu-Carmic-32bit (g ++ v4.4.1)

  • save example as customExc.cpp
  • type make customExc.o

EDIT : The error is related to CustomException . The Foo class has nothing to do with it. So I deleted it.

+7
c ++ const g ++
source share
4 answers

CustomException::what throws CustomException::code . CustomException::what is the const method, denoted by the constant after what() . Since this is a const method, it cannot do anything that it can change itself. CustomException::code not a const method, which means that it does not promise not to modify itself. Therefore, CustomException::what cannot raise CustomException::code .

Note that const methods are not necessarily associated with const instances. Foo::bar can declare its variable exc as non-constant and a method for calling const, such as CustomException::what ; it just means that CustomException::what promises does not change the exc , but different code can be used.

C ++ FAQs contain more detailed information about const methods .

+14
source share
  int code() const { return 42; } 
+4
source share

Your what() is a const member function, but code() not.

Just change code() to code() const .

+3
source share

Your code() member function is not declared const. Calling non-const member functions from member member functions ( what() in this case) is illegal.

Make your code() const member.

+3
source share

All Articles