Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Is there a way to call member function of a class without the class object on left hand side?</p> <p>...</p> <p>so, is there a way (or hack) to call <code>D::foo</code> with class object passed to it as function argument instead of using <code>.</code> or <code>-&gt;</code> or <code>.*</code> or <code>-&gt;*</code> operators on class object?</p> </blockquote> <p>In short, no. You cannot call a non-<code>static</code> class member function without somehow specifying the object on the left side of the call. If the class (for static functions) or the object (for non-static) is not specified, the compiler has no way of knowing which function you are trying to call. It's outside the current scope because it's inside a class or object. There are ways to "hack" code so you can write it to look like <code>main()</code> in your example. Some of the other answers give examples of just these kinds of hacks.</p> <p>------------Using static functions-----------------</p> <p>A function within a class <em>can</em> be called outside the class without specifying a class object. The way to do it is to create a <code>typedef</code> for a function pointer with a signature that matches the class function's, then creating such a pointer and assigning it the address of the class function. That function can then be called without needing to specify the class or an object on the left side.</p> <p>The function <strong>must</strong> be <code>static</code>. ISO C++ does not allow taking the address of a bound member function to form a pointer to that function, i.e. you cannot create a pointer to a non-<code>static</code> member function from a class object. You may be able to find some non-ISO standard compliant compilers, but I don't have any guidance on that for you.</p> <p>The parameter <code>this</code> to non-<code>static</code> class member functions is an implied parameter, and is always an implied parameter. You cannot manually specify it, but you <em>can</em> emulate it by passing a pointer to an object of the class.</p> <p>So, for your code example:</p> <ul> <li><code>void D::foo(int)</code> should be <code>static</code> and have an added <code>D*</code> parameter: <code>class D { static void D::foo(D*, int); };</code>.</li> <li><code>typedef void (D::* Func)(int);</code> should be changed to accommodate the previous change and remove <code>D::</code>: <code>typedef void (*Func)(D*, int);</code></li> </ul>
 

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