How to call a non static function from a static function

  • Thread starter bhattacharjeesoft
  • Start date
B

bhattacharjeesoft

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.
 
I

Ian Collins

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 can't unless you pass an object of your class to the static
function. Which then begs the design question "Should I be using a
static member function?"
 
J

Jonathan Mcdougall

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,289
Messages
2,571,448
Members
48,126
Latest member
ToneyChun2

Latest Threads

Top