Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is calling a non-<code>const</code> function <code>test2.test()</code> on a <code>const</code> object <code>test2</code> from <code>testing::test1</code>.</p> <p><code>testing::test1</code> gets <code>test2</code> as a parameter <code>const testing &amp;test2</code>. So within <code>testing::test1</code>, <code>test2const</code>. Then in the first line of the function:</p> <pre><code>test2.test() </code></pre> <p>The <code>testing::test</code> function is called on <code>test2</code>. That function is not declared with <code>const</code> at the signature end, so it may modify the object it is called on (the <code>this</code> pointer 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 a <code>const</code> variable without an explicit cast, which C++ is not supposed to allow. <strong>Therefore to explain the error message</strong>:</p> <pre><code>test.cpp:15: error: passing ‘const testing’ as ‘this’ argument of ‘int testing::test()’ discards qualifiers </code></pre> <p><code>this</code> refers to the object the member function (<code>testing::test</code>) operates on, and in this case it is not <code>const</code>, because <code>testing::test</code> was not declared with <code>const</code>, and thus the mismatch is detected when trying to make a non-<code>const</code> pointer (<code>this</code>) refer to a <code>const</code> object (<code>testing</code>), ignoring the <code>const</code> <em>qualifier</em>.</p> <p><strong>To solve this</strong>, decide whether the <code>testing::test</code> function should ever need to modify the object it is called on (the way it is written now it does not, as all it does is <code>return 1</code>, however that may change, so you need to think at what its intended functionality is). If it should, then obviously calling it on a <code>const</code> object is bad, although you can use <code>const_cast</code> to ask the compiler to override that, but this is dangerous. If it should not, then mark it <code>const</code>, so that it can be called on <code>const</code> objects as well:</p> <pre><code>class testing{ int test1() const; // ... } int testing::test() const { // ... } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload