Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You really want to call a member function without using <code>.</code> or <code>-&gt;</code>? Really, <strong>really</strong>? Well, okay...</p> <p>Evil.h:</p> <pre><code>#ifdef __cplusplus extern "C" { #endif struct MyStruct { #ifdef __cplusplus MyStruct(); void method(int); #endif }; #ifdef __cplusplus } #endif </code></pre> <p>Evil.cc:</p> <pre><code>#include &lt;iostream&gt; #include "evil.h" MyStruct::MyStruct() { std::cout &lt;&lt; "This is MyStruct's constructor" &lt;&lt; std::endl; } void MyStruct::method(int i) { std::cout &lt;&lt; "You passed " &lt;&lt; i &lt;&lt; std::endl; } </code></pre> <p>Evil.c:</p> <pre><code>#include "evil.h" int main() { struct MyStruct my_struct; _ZN8MyStructC1Ev(&amp;my_struct); /* MyStruct::MyStruct() */ _ZN8MyStruct6methodEi(&amp;my_struct, 3); /* MyStruct::method(int) */ return 0; } </code></pre> <p>This happens to work for my combination of gcc and g++ on Linux, but needless to say it relies on the platform ABI, and violates the C89 standard in calling functions of the form <em>underscore-capital letter</em>. It almost certainly won't work with virtual functions, and I'm not inclined to try. It may also be the most evil thing I've ever written. But still...</p> <hr> <p>EDIT: To quote the OP:</p> <blockquote> <p>In my mind, at end of the day (at assembly/binary level) all member functions of a class are normal functions which should operate on n + 1 arguments where (+1 is for <code>this</code>)</p> </blockquote> <p>While it's true that every compiler since CFront has done it this way, that's just an implementation detail. The C++ standard is at pains <strong>not</strong> to specify how member functions should implemented, just how they should behave.</p> <p>Because it's an implementation detail, different platforms do it in different ways. This goes beyond just name mangling. For example, the calling convention used on Linux specifies that <code>this</code> is passed as the first argument; other implementations (Borland, IIRC?) pass <code>this</code> as the <em>last</em> argument.</p> <p>So, if you want to treat member functions as ordinary functions with an extra <code>this</code>, then you have to restrict yourself to a particular ABI. This post serves an example of how you might do that (or rather, an example of why you really shouldn't do that!)</p> <blockquote> <p>so, is there a way (or hack) to call D::foo with class object passed to it as function argument instead of using . or -> or .* or ->* operators on class object?</p> </blockquote> <p>A platform-specific, disgusting dirty hack...</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