function pointers

I have been using the javascript to call a function via the attributes like so:

let hello = function(){
    console.log("saying hello")
}


let anothercaller = function (fn) {
    console.log(`calling function name hello`)
    fn()
}

anothercaller(hello)

This is dooable on cpp too using function pointers, which of course would be more efficient as you wouldn’t need to copy the function over to be called within the other function.

Here is the code

#include <iostream>
#include <string>

//define the functions...
int add(int, int);

int sum(int (*padd)(int, int), int, int);

int main() {
    int result{};
    //define the pointer function using (&<pfunctionName>)(attr)
    int (*p_add)(int, int);
    //allocate it here
    p_add = add;

    //another way to initialise the pointer function
    int (*p_add2)(int, int){add};

    //output the result
    std::cout << p_add(1, 2) << std::endl;
    std::cout << p_add2(1, 2) << std::endl;
    std::cout << p_add2 << std::endl; // print out the address of p_add2

    // pass p_add2 as a reference to sum to process the function, this is used instead of copying the function over.
    std::cout << sum(p_add2, 1, 2) << std::endl;

    return 0;
}
// basic addition
int add(int x, int y) {
    return x + y;
}

// basic addition using add reference
int sum(int (*p_add3)(int, int), int x, int y) {
    return p_add3(x, y);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.