Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a function to call the function that called it?

Tags:

c++

I would like the following simple function to call the function that called it, however the function is called by multiple functions, so it needs to recognize which function called it specifically and then call it.

int wrong()
{
    std::cout << "WRONG \n";
    return 0;
}

As a follow up, is this the sort of function that would be better expressed as a void?

like image 882
ticklemyiguana Avatar asked Dec 05 '15 01:12

ticklemyiguana


1 Answers

What you want is a callback. Callbacks are implemented like this in C++:

typedef int (*CallbackType)( char c );  

int wrong( CallbackType callback )
{
    std::cout << "WRONG \n";
    int r = callback( 'x' );
    return r;
}

int also_wrong( char c )
{
    return wrong( also_wrong );
}

Of course this will result in runaway recursion, so it will get you into a lot of trouble, but it definitely answers your question.

And yes, if all it does is to return 0, then this is the sort of function that would be better expressed as returning void.

like image 82
Mike Nakis Avatar answered Sep 28 '22 03:09

Mike Nakis