Below method of calling D::foo
function via pointer-to-member function will generate error: must use .*
or ->*
to call pointer-to-member function in 'f (...)'
.. of course that is not how we call pointer-to-member functions.
The correct way of calling is (d.*f)(5);
OR (p->*f)(5);
My question is, 'Is there a way to call member function of a class without the class object on left hand side? I wonder if we could pass class object (this
) as regular argument?
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 this
)
If we talk about D::foo
function below, at assembly/binary level it should operate on two arguments:
- The class object itself (pointer to class D object called
this
) - and the
int
.
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?
Sample Code:
#include <iostream>
using namespace std;
class D {
public:
void foo ( int a ) {
cout << "D" << endl;
}
int data;
};
//typedef void __cdecl ( D::* Func)(int);
typedef void ( D::* Func)(int);
int main ( void )
{
D d;
Func f = &D::foo;
f(&d, 5);
return 1;
}
One method is using boost bind i.e
(boost:: bind (&D::foo, &d, 5)) ();
EDIT: "Please note I am not looking for a version of this program which works, I know how to make it work"
bind
result type'soperator()
will be something like(ptr->*fun)(arg)
; you just don't see it because it's buried in the library implementation. – Kathleenkathlene;
after a statement is an "artificial restriction." It's just the syntax of the language. – Fretthis
value, not necessarily in that order. Non-static member functions might very well use a different calling convention from non-member functions. So it's not necessarily the same as calling a regular function withthis
as the first parameter, becausethis
might be passed in a different register or stack slot from where the first parameter would normally be passed. – Nomadicbind
itself doesn't call the function. I meant that the object returned bybind
has anoperator()
, which calls the function. No magic; just a class with an overloaded operator. – Kathleenkathlene