I'am developing a library, that can't use Classes. I have a function I call when a get a KeyDown event and i want to call a function that i set the prototype for before in the library. The thing is, I don't want to be mandatory for the user to define this function if he doesn't want to handle any input. But the linker won't let me define a prototype without a definition or set a default empty definition. What can i do? I'am using C++ by the way...
This are the prototypes /
void keyDown(int virtual_keyCode);
void keyUp(int virtual_keyCode);
Redefining a function is not possible in C++. Read this about the One Definition Rule.
Only one definition of any variable, function, class type, enumeration type, concept (since C++20) or template is allowed in any one translation unit (some of these may have multiple declarations, but only one definition is allowed).
Overloading of class functions is possible with inheritance. Overloading is not the same as redefinition.
You can use function pointers, which you can reassign, e.g.
#include<functional>
#include<iostream>
std::function<void(int)> keyUp = [](int) {};
void unused() {
keyUp(2);
}
void KeyUp(int i) {
std::cout << i << i << '\n';
}
int main() {
unused(); // no print
keyUp = [](int i) { std::cout << i << '\n'; };
unused(); // prints 2
keyUp = KeyUp;
unused(); // prints 22
}
It doesn't look the same, but effectively its the same...