Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>A const member function, is a member function that does not mutate its member variables.</strong> </p> <p><strong>const on a member function does not imply const char *. Which would mean that you can't change the data in the address the pointer holds.</strong> </p> <p>Your example does not mutate the member variables themselves.</p> <p>A const on a member function, will ensure that you treat all of your member variables as const. </p> <p>That means if you have:</p> <pre><code>int x; char c; char *p; </code></pre> <p>Then you will have:</p> <pre><code>const int x; const char c; char * const p; //&lt;-- means you cannot change what p points to, but you can change the data p points to </code></pre> <p>There are 2 types of const pointers. A const member function uses the one I've listed above. </p> <hr> <p><strong>A way to get the error you want:</strong></p> <p>Try changing:</p> <pre><code>char * rep; </code></pre> <p>to:</p> <pre><code>char rep[1024]; </code></pre> <p>And remove this line:</p> <pre><code>rep = new char [strlen(s)+1]; </code></pre> <p>It will throw the error you are expecting (can't modify members because of const keyword)</p> <p>Because there is only 1 type of const array. And that means you cannot modify any of its data. </p> <hr> <p>Now the whole system is actually broken with the following example:</p> <pre><code>class String { private: char rep2[1024]; char* rep; ... String :: String (const char* s) { rep = rep2; strcpy (rep, s); } </code></pre> <p><strong>So the lesson to learn here is that the const keyword on member functions does not ensure that your object will not change at all.</strong> </p> <p>It only ensures that each member variable will be treated as const. And for pointers, there is a big diff between const char * and char * const.</p> <p>Most of the time a const member function will mean that the member function will not modify the object itself, but this is not always the case, as the above example shows. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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