Re: How to call a non static function from a static function
On Aug 6, 9:07 am, bhattacharjees...@gmail.com wrote:
Hi
I need to go to a non static function from a static
function?can anybody suggest me how to do it?any kind of help
will be greatly appreciated.
You need to give more information about that static function.
How is it called? Why do you need one in the first place?
class example
{
public:
static void static_member()
{
}
void nonstatic_member()
{
}
};
int main()
{
example e1, e2;
example::static_member();
}
In this example, on which object (e1 or e2) should this
nonstatic member function be called?
Most of the times, this question arises because a static member
function is passed to an API that expects a free function,
such as when creating a thread. Most of these APIs will also
provide a way of passing user-defined information. You could
pass the address of an object, pick it up in your static
member function and then call the appropriate nonstatic member
function on it:
class example
{
public:
static void thread_fun(void* v)
{
example* e = reinterpret_cast<example*>(v);
e->run();
}
private:
void run()
{
}
};
int main()
{
example e;
// create_thread() is a fictitious API function which
// takes the address of a "callback" and an additional
// pointer value
create_thread(&example::thread_fun, &e);
// here, care must be taken to make sure 'e' will stay
// alive until the thread finishes, usually by 'joining' the
// thread.
}
If the API does not provides any means of passing additional
information to the static member function, you'll need to
devise a way yourself.
Jonathan Mcdougall