Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does the Visual C++ compiler pass the this ptr to the called function?
    text
    copied!<p>I'm learning C++ using Eckel's "Thinking in C++". It states the following:</p> <ul> <li>If a class contains virtual methods, a virtual function table is created for that class etc. The workings of the function table are explained roughly. (I know a vtable is not mandatory, but Visual C++ creates one.)</li> <li>The calling object is passed to the called function as an argument. (This might not be true for Visual C++ (or any compiler).) I'm trying to find out how VC++ passes the calling object to the function. </li> </ul> <p>To test both points in Visual C++, I've created the following class (using Visual Studio 2010, WinXP Home 32bit):</p> <p>ByteExaminer.h:</p> <pre><code>#pragma once class ByteExaminer { public: short b[2]; ByteExaminer(void); virtual void f() const; virtual void g() const; void bruteFG(); }; </code></pre> <p>ByteExaminer.cpp:</p> <pre><code>#include "StdAfx.h" #include "ByteExaminer.h" using namespace std; ByteExaminer::ByteExaminer(void) { b[0] = 25; b[1] = 26; } void ByteExaminer::f(void) const { cout &lt;&lt; "virtual f(); b[0]: " &lt;&lt; hex &lt;&lt; b[0] &lt;&lt; endl; } void ByteExaminer::g(void) const { cout &lt;&lt; "virtual g(); b[1]: " &lt;&lt; hex &lt;&lt; b[1] &lt;&lt; endl; } void ByteExaminer::bruteFG(void) { int *mem = reinterpret_cast&lt;int*&gt;(this); void (*fg[])(ByteExaminer*) = { (void (*)(ByteExaminer*))(*((int *)*mem)), (void (*)(ByteExaminer*))(*((int *)(*mem + 4))) }; fg[0](this); fg[1](this); } </code></pre> <p>The navigation through the vtable in <code>bruteFG()</code> works - when I call <code>fg[0](this)</code>, <code>f()</code> is called. What does NOT work, however, is the passing of <code>this</code> to the function - meaning that <code>this-&gt;b[0]</code> is not printed correctly (garbage comes out instead. I'm actually lucky this doesn't produce a segfault). </p> <p>So the actual output for </p> <pre><code>ByteExaminer be; be.bruteFG(); </code></pre> <p>is:</p> <pre><code>virtual f(); b[0]: 1307 virtual g(); b[1]: 0 </code></pre> <p>So how should I proceed to get the correct result? How are the <code>this</code> pointers passed to functions in VC++?</p> <p>(Nota bene: I'm NOT going to program this way seriously, ever. This is "for the lulz"; or for the learning experience. So don't try to convert me to proper C++ianity :))</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