Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Consider a variation of your class <code>A</code>.</p> <pre><code>class A { public: void Foo() const; void Moo(); private: int m_nState; // Could add mutable keyword if desired int GetState() const { return m_nState; } void SetState(int val) { m_nState = val; } }; const A *A1 = new A(); A *A2 = new A(); A1-&gt;Foo(); // OK A2-&gt;Foo(); // OK A1-&gt;Moo(); // Error - Not allowed to call non-const function on const object instance A2-&gt;Moo(); // OK </code></pre> <p>The <code>const</code> keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of <code>A</code>. Thus you are unable to call non-<code>const</code> functions within <code>A::Foo</code> nor change the value of member variables.</p> <p>To illustrate, <em>Foo()</em> may not invoke <code>A::SetState</code> as it is declared non-<code>const</code>, <code>A::GetState</code> however is ok because it is explicitly declared <code>const</code>. The member <code>m_nState</code> may not be changed either unless declared with the keyword <code>mutable</code>.</p> <p>One example of this usage of <code>const</code> is for 'getter' functions to obtain the value of member variables.</p> <blockquote> <p>@1800 Information: I forgot about mutable!</p> </blockquote> <p>The <code>mutable</code> keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.</p>
 

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