0

I was going through the glfw documentation and came across this piece of code. I am relatively new to c++ and am curious to what was going on here. If I do cout << key_callback << endl; I get something that looks like a memory address. What exactly is at this memory location and when is passing a static method as a parameter useful? Thank you ahead of time!

    class Foo{
    Public:
    Private:
        glfwSetKeyCallback(window, key_callback);
    
        static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
        {
            if (key == GLFW_KEY_E && action == GLFW_PRESS)
                activate_airship();
        }
    };
Geno C
  • 1,401
  • 3
  • 11
  • 26
hairystew
  • 1
  • 1
  • https://en.wikipedia.org/wiki/Callback_(computer_programming) – 0x5453 Aug 05 '20 at 21:53
  • The address you are seeing is the address in memory where the function lives. The compiled code lives there. Passing a method as a parameter is a pattern more common in the C language, that allows you to provide specific behavior to, say, a more generic piece of code. For instance you may have actions to perform when memory is freed, so you pass a function pointer to code that needs to free memory and when it does it calls your function so you can take care of any bookkeeping instead of the standard free(). C++ nowadays often favors lambdas or std::function objects to do similar behavior. – Durstann Aug 06 '20 at 04:59

1 Answers1

0

It's the function's memory address as you already stated.

You can imagine that every variable, object, function - even each line of code - has a distinct address in the memory. When your program executes and hit's a function, it's "jumping" to that address and executes the code which is present there (this is a really rough approximation - If you like to learn more about it, follow this link).

Static is kind of an edge case. While there are global functions, and object methods (which belong to the object itself) static functions belong to class they are defined in. They are only once in memory no matter how many objects there are (0-infinite).

Passing functions as parameters (without any restrictions of being static or non-static) are quite useful when programming complex scenarios.

Imagine you like to write a "generic sort" function for objects. How could you implement just the sort without knowing the object (and therefore the attributes) or the order (ascending, descending)? This is when function parameters come in. You can define your sort function to work with a function callback that handles the data retrieval from the object as well as how to "compare" objects with each other. It also allows you to change behavior with a parameter (e.g. the operation in a calculator program. There are always two operands and only the operation changes).

Alex
  • 1,857
  • 3
  • 36
  • 51