Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>this</code> pointer is not a member of the class. It's just a construct that is used in methods belonging to the class to refer to the current instance.</p> <p>If you have a class like this:</p> <pre><code>class IntPair { public: IntPair(int a, int b) : _a(a), _b(b) { } int sum() const { return _a + _b; } public: int _a; int _b; }; </code></pre> <p>This class only needs space for two instances of <code>int</code> for each instance. Once you've created an instance and are running the <code>sum()</code> method, that method is called with a pointer to the instance, but that pointer always comes from somewhere else, it isn't stored in the object instance.</p> <p>For example:</p> <pre><code>IntPair *fib12 = new IntPair(89, 144); cout &lt;&lt; fib12-&gt;sum(); </code></pre> <p>Notice how the variable that becomes the <code>this</code> pointer is stored <em>outside</em> the object, in the scope that created it.</p> <p>You could, in fact, always transform a method like the one above into:</p> <pre><code>static int sum2(const IntPair* instance) { return instance-&gt;_a + instance-&gt;_b; } </code></pre> <p>If the above is defined inside the class (so it can access the private members), there's no difference. In fact, this <em>is</em> how methods are implemented behind the scene; the <code>this</code> pointer is just a hidden argument to all member methods.</p> <p>The call would become:</p> <pre><code>IntPair* fib12 = new IntPair(89, 144); cout &lt;&lt; IntPair::sum2(fib12); </code></pre>
    singulars
    1. This table or related slice is empty.
    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