Call up functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • masterofthebus
    New Member
    • Jan 2008
    • 2

    Call up functions

    Hi everyone,

    I have a question that is tricking me.

    I need to do something like this:
    -----------------------------------------------------------

    Code:
    int a;
    
    
    void* function(const &function){
        //execute the code of the function here that i sent the address
    }
    
    int main(){
           a = 0 ;
    
           call(&myFunction);
    
        cout << a ;
    }
    ----------------------

    I don't know if i explained it well but what I need is a function to call another functions by its adress. For example, I use call(&function2 ); then it runs all function2()

    .
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You need a function pointer.

    That is, your call() needs an argument that is a pointer to a function that has the correct arguments and return type.
    [code=cpp]
    void AFunction(int x, float y)
    {
    //etc...
    {
    [/code]
    A pointer to this function would be:
    [code=cpp]
    void (*fp)(int, float);
    [/code]

    Then you can assign the address of AFunction to this pointer:
    [code=cpp]
    fp = AFunction;
    [/code]

    The name of a function is the address of the function so you not code &AFunction.

    Then, your call() just has to have a function pointer argument:
    [code=cpp]
    void call(void (*fp)(int, float))
    {
    //etc...
    }
    [/code]

    Finally, in main() you can make the call:
    [code=cpp]
    call(AFunction) ;
    [/code]

    Remember, the argments and return type declared in your function pointer must match those of the actual function or you cannot put that function's address into the pointer.

    Comment

    Working...