The problem is calling the const function not const for the const test2 from testing::test1 .
testing::test1 receives test2 as the const testing &test2 . So, inside testing::test1 , test2const . Then in the first line of the function:
test2.test()
The testing::test function is called on test2 . This function is not declared with const at the end of the signature, so it can change the object to which it is called (the this pointer, implicitly passed to it), and even if it is not, the compiler assumes this. Letting you name it there, the compiler will let you change the const variable without an explicit cast, which C ++ does not allow. Therefore, to explain the error message :
test.cpp:15: error: passing 'const testing' as 'this' argument of 'int testing::test()' discards qualifiers
this refers to the object on which the member function acts ( testing::test ), and in this case it is not const , because testing::test not declared using const , and thus a mismatch was detected when trying to make a pointer not const ( this ) refers to a const ( testing ) object, ignoring the const qualifier.
To solve this problem , decide whether the testing::test function is needed to change the object it is called on (the way it is now written is not so, since all it does is return 1 , however this can change, so you need to think about what its intended functionality is). If so, then it is obvious that calling it on a const object is bad, although you can use const_cast to ask the compiler to override this, but it is dangerous. If this is not the case, then mark it with const so that it can also be called in const objects:
class testing{ int test1() const;
Tom Alsberg Feb 15 '09 at 6:45 2009-02-15 06:45
source share