Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>int &amp; geta(void) const { return *a; } // good? int &amp; getb(void) const { return b; } // obviously bad </code></pre> <p>In a const-function, every data member becomes const <strong>in such way that it cannot be modified</strong>. <code>int</code> becomes <code>const int</code>, <code>int *</code> becomes <code>int * const</code>, and so on. </p> <p>Since the <em>type</em> of <code>a</code> in your first function becomes <code>int * const</code>, as opposed to <code>const int *</code>, so you can change the data (which is modifiable):</p> <pre><code> m.geta() = 5; //works, as the data is modifiable </code></pre> <p>Difference between : <code>const int*</code> and <code>int * const</code>.</p> <ul> <li><code>const int*</code> means the pointer is <strong>non-const</strong>, but the data the pointer points to is <strong>const</strong>.</li> <li><code>int * const</code> means the pointer is <strong>const</strong>, but the data the pointer points to is <strong>non-const</strong>.</li> </ul> <p>Your second function tries to return <code>const int &amp;</code>, since the <em>type</em> of <code>b</code> become <code>const int</code>. But you've mentioned the actual return type in your code as <code>int &amp;</code>, so this function would <strong>not</strong> even compile (see <a href="http://www.ideone.com/xjE8E">this</a>), irrespective of what you do in <code>main()</code>, because the return <em>type</em> doesn't match. Here is the fix:</p> <pre><code> const int &amp; getb(void) const { return b; } </code></pre> <p>Now it <a href="http://www.ideone.com/J2eLN">compiles fine!</a>.</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.
    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