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"