I’m having some trouble with a particular piece of code, if anyone can enlighten me on this matter it would be greatly appreciated, I’ve isolated the problem down in the following sample:
#include <iostream> using namespace std; class testing{ int test(); int test1(const testing& test2); }; int testing::test(){ return 1; } int testing::test1(const testing& test2){ test2.test(); return 1; }
So what could possibly have cause the following error:
test.cpp:15: error: passing ‘const testing’ as ‘this’ argument of ‘int testing::test()’ discards qualifiers
Thanks a lot!
The problem is calling a non-
constfunctiontest2.test()on aconstobjecttest2fromtesting::test1.testing::test1getstest2as a parameterconst testing &test2. So withintesting::test1,test2const. Then in the first line of the function:The
testing::testfunction is called ontest2. That function is not declared withconstat the signature end, so it may modify the object it is called on (thethispointer implicitly passed to it), and even though it does not, the compiler assumes so. By letting you call it there, the compiler would let you modify aconstvariable without an explicit cast, which C++ is not supposed to allow. Therefore to explain the error message:thisrefers to the object the member function (testing::test) operates on, and in this case it is notconst, becausetesting::testwas not declared withconst, and thus the mismatch is detected when trying to make a non-constpointer (this) refer to aconstobject (testing), ignoring theconstqualifier.To solve this, decide whether the
testing::testfunction should ever need to modify the object it is called on (the way it is written now it does not, as all it does isreturn 1, however that may change, so you need to think at what its intended functionality is). If it should, then obviously calling it on aconstobject is bad, although you can useconst_castto ask the compiler to override that, but this is dangerous. If it should not, then mark itconst, so that it can be called onconstobjects as well: