why do I get a 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
on 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 have searched around on SOF before regarding simular issues.
I have already added a const on every possible place.
Please enlighten me – I don’t get the point…
EDIT:
here are the steps to reproduce 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 class Foo has nothing to do with it. So I have deleted it.
CustomException::whatcallsCustomException::code.CustomException::whatis a const method, as signified by the const afterwhat(). Since it is a const method, it cannot do anything that may modify itself.CustomException::codeis not a const method, which means that it does not promise to not modify itself. SoCustomException::whatcan’t callCustomException::code.Note that const methods are not necessarily related to const instances.
Foo::barcan declare itsexcvariable as non-const and call const methods likeCustomException::what; this simply means thatCustomException::whatpromises not to modifyexc, but other code might.The C++ FAQ has a bit more information on const methods.