I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors.
Here is what I did from my constructor:
m_cRedundencyManager->Init(this->RedundencyManagerCallBack);
This doesn't compile - I get the following error:
Error 8 error C3867: 'CLoggersInfra::RedundencyManagerCallBack': function call missing argument list; use '&CLoggersInfra::RedundencyManagerCallBack' to create a pointer to member
I tried the suggestion to use &CLoggersInfra::RedundencyManagerCallBack - didn't work for me.
Any suggestions/explanation for this??
I'm using VS2008.
Thanks!!
This is a simple question but the answer is surprisingly complex. The short answer is you can do what you're trying to do with std::bind1st or boost::bind. The longer answer is below.
The compiler is correct to suggest you use &CLoggersInfra::RedundencyManagerCallBack. First, if RedundencyManagerCallBack is a member function, the function itself doesn't belong to any particular instance of the class CLoggersInfra. It belongs to the class itself. If you've ever called a static class function before, you may have noticed you use the same SomeClass::SomeMemberFunction syntax. Since the function itself is 'static' in the sense that it belongs to the class rather than a particular instance, you use the same syntax. The '&' is necessary because technically speaking you don't pass functions directly -- functions are not real objects in C++. Instead you're technically passing the memory address for the function, that is, a pointer to where the function's instructions begin in memory. The consequence is the same though, you're effectively 'passing a function' as a parameter.
But that's only half the problem in this instance. As I said, RedundencyManagerCallBack the function doesn't 'belong' to any particular instance. But it sounds like you want to pass it as a callback with a particular instance in mind. To understand how to do this you need to understand what member functions really are: regular not-defined-in-any-class functions with an extra hidden parameter.
For example:
class A {
public:
A() : data(0) {}
void foo(int addToData) { this->data += addToData; }
int data;
};
...
A an_a_object;
an_a_object.foo(5);
A::foo(&an_a_object, 5); // This is the same as the line above!
std::cout << an_a_object.data; // Prints 10!
How many parameters does A::foo take? Normally we would say 1. But under the hood, foo really takes 2. Looking at A::foo's definition, it needs a specific instance of A in order for the 'this' pointer to be meaningful (the compiler needs to know what 'this' is). The way you usually specify what you want 'this' to be is through the syntax MyObject.MyMemberFunction(). But this is just syntactic sugar for passing the address of MyObject as the first parameter to MyMemberFunction. Similarly, when we declare member functions inside class definitions we don't put 'this' in the parameter list, but this is just a gift from the language designers to save typing. Instead you have to specify that a member function is static to opt out of it automatically getting the extra 'this' parameter. If the C++ compiler translated the above example to C code (the original C++ compiler actually worked that way), it would probably write something like this:
struct A {
int data;
};
void a_init(A* to_init)
{
to_init->data = 0;
}
void a_foo(A* this, int addToData)
{
this->data += addToData;
}
...
A an_a_object;
a_init(0); // Before constructor call was implicit
a_foo(&an_a_object, 5); // Used to be an_a_object.foo(5);
Returning to your example, there is now an obvious problem. 'Init' wants a pointer to a function that takes one parameter. But &CLoggersInfra::RedundencyManagerCallBack is a pointer to a function that takes two parameters, it's normal parameter and the secret 'this' parameter. That's why you're still getting a compiler error (as a side note: If you've ever used Python, this kind of confusion is why a 'self' parameter is required for all member functions).
The verbose way to handle this is to create a special object that holds a pointer to the instance you want and has a member function called something like 'run' or 'execute' (or overloads the '()' operator) that takes the parameters for the member function, and simply calls the member function with those parameters on the stored instance. But this would require you to change 'Init' to take your special object rather than a raw function pointer, and it sounds like Init is someone else's code. And making a special class for every time this problem comes up will lead to code bloat.
So now, finally, the good solution, boost::bind and boost::function, the documentation for each you can find here:
boost::bind docs,
boost::function docs
boost::bind will let you take a function, and a parameter to that function, and make a new function where that parameter is 'locked' in place. So if I have a function that adds two integers, I can use boost::bind to make a new function where one of the parameters is locked to say 5. This new function will only take one integer parameter, and will always add 5 specifically to it. Using this technique, you can 'lock in' the hidden 'this' parameter to be a particular class instance, and generate a new function that only takes one parameter, just like you want (note that the hidden parameter is always the first parameter, and the normal parameters come in order after it). Look at the boost::bind docs for examples, they even specifically discuss using it for member functions. Technically there is a standard function called [std::bind1st][3] that you could use as well, but boost::bind is more general.
Of course, there's just one more catch. boost::bind will make a nice boost::function for you, but this is still technically not a raw function pointer like Init probably wants. Thankfully, boost provides a way to convert boost::function's to raw pointers, as documented on StackOverflow here. How it implements this is beyond the scope of this answer, though it's interesting too.
Don't worry if this seems ludicrously hard -- your question intersects several of C++'s darker corners, and boost::bind is incredibly useful once you learn it.
C++11 update: Instead of boost::bind you can now use a lambda function that captures 'this'. This is basically having the compiler generate the same thing for you.
That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.
Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:
m_cRedundencyManager->Init(&CLoggersInfra::Callback, this);
The function can be defined as follows
static void Callback(int other_arg, void * this_pointer) {
CLoggersInfra * self = static_cast<CLoggersInfra*>(this_pointer);
self->RedundencyManagerCallBack(other_arg);
}
This answer is a reply to a comment above and does not work with VisualStudio 2008 but should be preferred with more recent compilers.
Meanwhile you don't have to use a void pointer anymore and there is also no need for boost since std::bind and std::function are available. One advantage (in comparison to void pointers) is type safety since the return type and the arguments are explicitly stated using std::function:
// std::function<return_type(list of argument_type(s))>
void Init(std::function<void(void)> f);
Then you can create the function pointer with std::bind and pass it to Init:
auto cLoggersInfraInstance = CLoggersInfra();
auto callback = std::bind(&CLoggersInfra::RedundencyManagerCallBack, cLoggersInfraInstance);
Init(callback);
Complete example for using std::bind with member, static members and non member functions:
#include <functional>
#include <iostream>
#include <string>
class RedundencyManager // incl. Typo ;-)
{
public:
// std::function<return_type(list of argument_type(s))>
std::string Init(std::function<std::string(void)> f)
{
return f();
}
};
class CLoggersInfra
{
private:
std::string member = "Hello from non static member callback!";
public:
static std::string RedundencyManagerCallBack()
{
return "Hello from static member callback!";
}
std::string NonStaticRedundencyManagerCallBack()
{
return member;
}
};
std::string NonMemberCallBack()
{
return "Hello from non member function!";
}
int main()
{
auto instance = RedundencyManager();
auto callback1 = std::bind(&NonMemberCallBack);
std::cout << instance.Init(callback1) << "\n";
// Similar to non member function.
auto callback2 = std::bind(&CLoggersInfra::RedundencyManagerCallBack);
std::cout << instance.Init(callback2) << "\n";
// Class instance is passed to std::bind as second argument.
// (heed that I call the constructor of CLoggersInfra)
auto callback3 = std::bind(&CLoggersInfra::NonStaticRedundencyManagerCallBack,
CLoggersInfra());
std::cout << instance.Init(callback3) << "\n";
}
Possible output:
Hello from non member function!
Hello from static member callback!
Hello from non static member callback!
Furthermore using std::placeholders you can dynamically pass arguments to the callback (e.g. this enables the usage of return f("MyString"); in Init if f has a string parameter).
What argument does Init take? What is the new error message?
Method pointers in C++ are a bit difficult to use. Besides the method pointer itself, you also need to provide an instance pointer (in your case this). Maybe Init expects it as a separate argument?
A pointer to a class member function is not the same as a pointer to a function. A class member takes an implicit extra argument (the this pointer), and uses a different calling convention.
If your API expects a nonmember callback function, that's what you have to pass to it.
Is m_cRedundencyManager able to use member functions? Most callbacks are set up to use regular functions or static member functions. Take a look at this page at C++ FAQ Lite for more information.
Update: The function declaration you provided shows that m_cRedundencyManager is expecting a function of the form: void yourCallbackFunction(int, void *). Member functions are therefore unacceptable as callbacks in this case. A static member function may work, but if that is unacceptable in your case, the following code would also work. Note that it uses an evil cast from void *.
// in your CLoggersInfra constructor:
m_cRedundencyManager->Init(myRedundencyManagerCallBackHandler, this);
// in your CLoggersInfra header:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr);
// in your CLoggersInfra source file:
void myRedundencyManagerCallBackHandler(int i, void * CLoggersInfraPtr)
{
((CLoggersInfra *)CLoggersInfraPtr)->RedundencyManagerCallBack(i);
}
Necromancing.
I think the answers to date are a little unclear.
Let's make an example:
Supposed you have an array of pixels (array of ARGB int8_t values)
// A RGB image
int8_t* pixels = new int8_t[1024*768*4];
Now you want to generate a PNG.
To do so, you call the function toJpeg
bool ok = toJpeg(writeByte, pixels, width, height);
where writeByte is a callback-function
void writeByte(unsigned char oneByte)
{
fputc(oneByte, output);
}
The problem here: FILE* output has to be a global variable.
Very bad if you're in a multithreaded environment (e.g. a http-server).
So you need some way to make output a non-global variable, while retaining the callback signature.
The immediate solution that springs into mind is a closure, which we can emulate using a class with a member function.
class BadIdea {
private:
FILE* m_stream;
public:
BadIdea(FILE* stream) {
this->m_stream = stream;
}
void writeByte(unsigned char oneByte){
fputc(oneByte, this->m_stream);
}
};
And then do
FILE *fp = fopen(filename, "wb");
BadIdea* foobar = new BadIdea(fp);
bool ok = TooJpeg::writeJpeg(foobar->writeByte, image, width, height);
delete foobar;
fflush(fp);
fclose(fp);
However, contrary to expectations, this does not work.
The reason is, C++ member functions are kinda implemented like C# extension functions.
So you have
class/struct BadIdea
{
FILE* m_stream;
}
and
static class BadIdeaExtensions
{
public static writeByte(this BadIdea instance, unsigned char oneByte)
{
fputc(oneByte, instance->m_stream);
}
}
So when you want to call writeByte, you need pass not only the address of writeByte, but also the address of the BadIdea-instance.
So when you have a typedef for the writeByte procedure, and it looks like this
typedef void (*WRITE_ONE_BYTE)(unsigned char);
And you have a writeJpeg signature that looks like this
bool writeJpeg(WRITE_ONE_BYTE output, uint8_t* pixels, uint32_t
width, uint32_t height))
{ ... }
it's fundamentally impossible to pass a two-address member function to a one-address function pointer (without modifying writeJpeg), and there's no way around it.
The next best thing that you can do in C++, is using a lambda-function:
FILE *fp = fopen(filename, "wb");
auto lambda = [fp](unsigned char oneByte) { fputc(oneByte, fp); };
bool ok = TooJpeg::writeJpeg(lambda, image, width, height);
However, because lambda is doing nothing different, than passing an instance to a hidden class (such as the "BadIdea"-class), you need to modify the signature of writeJpeg.
The advantage of lambda over a manual class, is that you just need to change one typedef
typedef void (*WRITE_ONE_BYTE)(unsigned char);
to
using WRITE_ONE_BYTE = std::function<void(unsigned char)>;
And then you can leave everything else untouched.
You could also use std::bind
auto f = std::bind(&BadIdea::writeByte, &foobar);
But this, behind the scene, just creates a lambda function, which then also needs the change in typedef.
So no, there is no way to pass a member function to a method that requires a static function-pointer.
But lambdas are the easy way around, provided that you have control over the source.
Otherwise, you're out of luck.
There's nothing you can do with C++.
Note:
std::function requires #include <functional>
However, since C++ allows you to use C as well, you can do this with libffcall in plain C, if you don't mind linking a dependency.
Download libffcall from GNU (at least on ubuntu, don't use the distro-provided package - it is broken), unzip.
./configure
make
make install
gcc main.c -l:libffcall.a -o ma
main.c:
#include <callback.h>
// this is the closure function to be allocated
void function (void* data, va_alist alist)
{
int abc = va_arg_int(alist);
printf("data: %08p\n", data); // hex 0x14 = 20
printf("abc: %d\n", abc);
// va_start_type(alist[, return_type]);
// arg = va_arg_type(alist[, arg_type]);
// va_return_type(alist[[, return_type], return_value]);
// va_start_int(alist);
// int r = 666;
// va_return_int(alist, r);
}
int main(int argc, char* argv[])
{
int in1 = 10;
void * data = (void*) 20;
void(*incrementer1)(int abc) = (void(*)()) alloc_callback(&function, data);
// void(*incrementer1)() can have unlimited arguments, e.g. incrementer1(123,456);
// void(*incrementer1)(int abc) starts to throw errors...
incrementer1(123);
// free_callback(callback);
return EXIT_SUCCESS;
}
And if you use CMake, add the linker library after add_executable
add_library(libffcall STATIC IMPORTED)
set_target_properties(libffcall PROPERTIES
IMPORTED_LOCATION /usr/local/lib/libffcall.a)
target_link_libraries(BitmapLion libffcall)
or you could just dynamically link libffcall
target_link_libraries(BitmapLion ffcall)
Note:
You might want to include the libffcall headers and libraries, or create a cmake project with the contents of libffcall.
A simple solution "workaround" still is to create a class of virtual functions "interface" and inherit it in the caller class. Then pass it as a parameter "could be in the constructor" of the other class that you want to call your caller class back.
DEFINE Interface:
class CallBack
{
virtual callMeBack () {};
};
This is the class that you want to call you back:
class AnotherClass ()
{
public void RegisterMe(CallBack *callback)
{
m_callback = callback;
}
public void DoSomething ()
{
// DO STUFF
// .....
// then call
if (m_callback) m_callback->callMeBack();
}
private CallBack *m_callback = NULL;
};
And this is the class that will be called back.
class Caller : public CallBack
{
void DoSomthing ()
{
}
void callMeBack()
{
std::cout << "I got your message" << std::endl;
}
};
It is still difficult to connect C style callback functions with C++ class instances. I want to kind of rephrase the original question:
Some library you are using requires a C style function to be called back from that library. Changing the library API is out of the question since it is not your API.
You want the callback to be handled in your own C++ code in member methods
As you did not mention (exactly) what callback you want to handle I will give an example using GLFW callbacks for key input. (On a side note: I know GLFW offers some other mechanism to attach user data to their API, but that is not the topic here.)
I don't know any solution to this problem that doesn't include usage of some kind of static object. Let's look at our options:
Simple approach: Use C style global objects
As we always think in classes and instances we sometimes forget that in C++ we still have the whole arsenal of C at our hands. So sometimes this very simple solution does not come to mind.
Let's assume we have a class Presentation that should handle keyboard input. This could look like this:
struct KeyInput {
int pressedKey;
} KeyInputGlobal;
void globalKeyHandler(GLFWwindow* window, int key, int scancode, int action, int mods) {
KeyInputGlobal.pressedKey = key;
}
int Presentation::getCurrentKey()
{
return KeyInputGlobal.pressedKey;
}
void Presentation::initGLFW()
{
glfwInit();
glfwSetKeyCallback(window, globalKeyHandler);
}
We have a global Object KeyInputGlobal that should receive the key pressed. The function globalKeyHandler has exactly the C style API signature needed by the GLFW library to be able to call our code. It is activated on our member method initGLFW. If anywhere in our code we are interested in the currently pressed key we can just call the other member method Presentation::getCurrentKey
What is wrong with this approach?
Maybe it is all fine. Depends entirely on your use case. Maybe you are totally fine to just read the last pressed key somwhere in your application code. You don't care to have missed key pressed events. The simple approach is all you need.
To generalize: If you are able to fully process the callback in C style code, calculate some result and store it in a global object to be read later from other parts of your code, then it may indeed make sense to use this simple approach. On the plus side: It is very simple to understand. The downside? It feels a little bit like cheating, because you didn't really process the callback in your C++ code, you just used the results. If you think of the callback as an event and want each event to be properly processed in your member methods this approch won't be enough.
Another simple approach: Use C++ static objects
I guess many of us have already done this. Certainly I have. Thinking: Wait, we have a C++ concept of globals, that is using static. But we can keep the discussion short here: It may be more C++ style than using the C style from previous example, but the problems are the same - we still have globals, that are hard to bring together with non-static, regular member methods. For completeness, it would look like this in our class declaration:
class Presentation
{
public:
struct KeyInput {
int pressedKey;
};
static KeyInput KeyInputGlobal;
static void globalKeyHandler(GLFWwindow* window, int key, int scancode, int action, int mods) {
KeyInputGlobal.pressedKey = key;
}
int getCurrentKey()
{
return KeyInputGlobal.pressedKey;
}
...
}
Activating our callback would look the same, but we also have to define the static struct that receives the key pressed in our implementation:
void Presentation::initGLFW()
{
glfwInit();
glfwSetKeyCallback(window, globalKeyHandler);
}
//static
Presentation::KeyInput Presentation::KeyInputGlobal;
You might be inclined to just remove the static keyword from our callback method globalKeyHandler: The compiler will immediately tell you that you can no longer pass this to GLFW in glfwSetKeyCallback(). Now, if we only could connect static methods with regular methods somehow...
C++11 Event driven approach with statics and lambdas
The best solution I could find out is the following. It works and is somewhat elegant, but I still do not consider it perfect. Let's look at it and discuss:
void Presentation::initGLFW()
{
glfwInit();
static auto callback_static = [this](
GLFWwindow* window, int key, int scancode, int action, int mods) {
// because we have a this pointer we are now able to call a non-static member method:
key_callbackMember(window, key, scancode, action, mods);
};
glfwSetKeyCallback(window,
[](GLFWwindow* window, int key, int scancode, int action, int mods)
{
// only static methods can be called here as we cannot change glfw function parameter list to include instance pointer
callback_static(window, key, scancode, action, mods);
}
);
}
void Presentation::key_callbackMember(GLFWwindow* window, int key, int scancode, int action, int mods)
{
// we can now call anywhere in our code to process the key input:
app->handleInput(key, action);
}
The definition of callback_static is where we connect a static object with instance data, in this case this is an instance of our Presentation class. You can read the definition as follows: If callback_static is called anytime after this definition, all parameters will be passed to the member method key_callbackMember called at the Presentation instance just used. This definition has nothing to do with the GLFW library yet - it is just the preparation for the next step.
We now use a second lambda to register our callback with the library in glfwSetKeyCallback(). Again, if callback_static would not have been defined as static we could not pass it to GLFW here.
This is what happens at runtime after all the initializations, when GLFW calls our code:
GLFW recognizes a key event and calls our static object callback_static
callback_static has access to an instance of Presentation class and calls it's instance method key_callbackMember
Now that we are in 'object world' we can process the key event somewhere else. In this case we call the method handleInput on some arbitrary object app, that has been setup somewhere else in our code.
The good: We have achieved what we wanted with no need to define global objects outside our initialization method initGLFW. No need for C style globals.
The bad: Don't be fooled just because everything is neatly packed into one method. We still have static objects. And with them all the problems global objects have. E.g. multiple calls to our initialization method (with different instances of Presentation) would probably not have the effect you intended.
Summary
It is possible to connect C style callbacks of existing libraries to instances of classes in your own code. You can try to minimize houeskeeping code by defining the necessary objects in member methods of your code. But you still need one static object for each callback. If you want to connect several instances of your C++ code with a C style callback be prepared to introduce a more complicated management of your static objects than in the example above.
Hope this helps someone. Happy coding.
I can see that the init has the following override:
Init(CALLBACK_FUNC_EX callback_func, void * callback_parm)
where CALLBACK_FUNC_EX is
typedef void (*CALLBACK_FUNC_EX)(int, void *);
The type of pointer to non-static member function is different from pointer to ordinary function.
Type is void(*)(int) if it’s an ordinary or static member function.
Type is void(CLoggersInfra::*)(int) if it’s a non-static member function.
So you cannot pass a pointer to a non-static member function if it is expecting an ordinary function pointer.
Furthermore, a non-static member function has an implicit/hidden parameter to the object. The this pointer is implicitly passed as an argument to the member function call. So the member functions can be invoked only by providing an object.
If the API Init cannot be changed, a wrapper function (ordinary function or a class static member function) that invokes the member can be used. In the worst case, the object would be a global for the wrapper function to access.
CLoggersInfra* pLoggerInfra;
RedundencyManagerCallBackWrapper(int val)
{
pLoggerInfra->RedundencyManagerCallBack(val);
}
m_cRedundencyManager->Init(RedundencyManagerCallBackWrapper);
If the API Init can be changed, there are many alternatives - Object non-static member function pointer, Function Object, std::function or Interface Function.
See the post on callbacks for the different variations with C++ working examples.
This question and answer from the C++ FAQ Lite covers your question and the considerations involved in the answer quite nicely I think. Short snippet from the web page I linked:
Don’t.
Because a member function is meaningless without an object to invoke
it on, you can’t do this directly (if The X Window System was
rewritten in C++, it would probably pass references to objects around,
not just pointers to functions; naturally the objects would embody the
required function and probably a whole lot more).
Looks like std::mem_fn (C++11) does exactly what you need:
Function template std::mem_fn generates wrapper objects for pointers to members, which can store, copy, and invoke a pointer to member. Both references and pointers (including smart pointers) to an object can be used when invoking a std::mem_fn.
I created a library in which one exposed function accepts a function pointer of type void(*fun_ptr)(int).
The function syntax is:
start_server(char *devices, char *folder, int number, int timeout, void(*status_of_server)(int));
This is working with normal C++ functions like void getStatus(int n); but when I used them in a Visual C++ environment for a GUI application, I'm getting this error:
A pointer to member is not valid for a managed class
start_server(&devs, &base, 1, 0, &TestApplication::MainWindow::StatusOfServer );
Where StatusOfServer is defined inside the MainWindow class which can be used for UI management.
private: void TestApplication::MainWindow::StatusOfServer(int n)
{
this->progressBar->Value = n;
}
What is the correct way of handling this?
The reason for the weird behavior is that each member function has implicitly appended to it's signature a pointer to it's type, e.g. :
#include <iostream>
struct S
{
int i;
void doSth() { std::cout << i << std::endl; }
};
int main()
{
S s{1};
s.doSth();
auto member_f = &S::doSth;
(s.*member_f)();
}
doSth() has a hidden parameter, so it can't be called like a regular function. In your example the situation is similar- you are trying to call member function as if it was a normal free function, which will not work. Usually in APIs requesting function pointers, the functions can take void* as parameter, which allows you to write a wrapper that will cast the pointer to the correct type and then invoke member function on the pointed to instance of the class. However from the code you've shown above, you can't pass void* into the function, so you'll have probably have some sort of global state (e.g. make that function static and let it work only on static data).
One solution would be to create a small non-managed wrapper function around the managed one:
void wrapStatusOfServer(int n) {
TestApplication::MainWindow::StatusOfServer(n)
}
and get a pointer to the wrapper
start_server(&devs, &base, 1, 0, &wrapStatusOfServer);
Another solution: turn your start_server into managed code and use a delegate instead of a function pointer: https://learn.microsoft.com/en-us/cpp/dotnet/how-to-define-and-use-delegates-cpp-cli?view=vs-2017
C++/CLI is fraught with this kind of issue, where managed and un-managed code and data are almost but not quite interoperable.
Can the same function be defined differently for different objects of the same class??
in A.h
class Hello{
public:
void myfunction();
}
main.cpp
Hello B0,B1;
// Here I want to define the function 'myfunction' for each object differently
int main(){
B0.myfunction();
B1.myfunction();
}
Is this possible?
Not directly, and I'd wonder why you want to do that if you really do want them to be objects of the same class type? This is what inheritance and virtual functions are for! If you want them to behave differently, you should make them different (but related) classes.
That said, I can think of one way to achieve something like this. std::function.
Have a class member like std::function<void(Hello*)> myfunctionimpl;, and then a member function void myfunction() { myfunctionimpl(this); }
Then in the constructor of Hello, you can set myfunctionimpl as a pointer to some other function, or with a lambda. For example, the following:
#include <functional>
#include <iostream>
class Hello {
public:
typedef std::function<void(Hello*)> MyFunctionType;
private:
MyFunctionType myfunctionimpl; // this holds the customisable function object
public:
Hello(const MyFunctionType& mf) // construct with a custom function object passed in
: myfunctionimpl(mf)
{}
Hello() // construct with a default function object
: myfunctionimpl([](Hello *h) {
std::cout << "Default function called on " << h << '\n';
})
{}
Hello(int){} // dummy to leave function object unset
void myfunction() {
// call the function object, only if it is safe to do so
if (this->myfunctionimpl) {
this->myfunctionimpl(this);
}
else {
std::cerr << "myfunctionimpl not set!\n";
}
}
};
void freeFunction(Hello*)
{
std::cout << "freeFunction\n";
}
int main()
{
Hello h1; // default
Hello h2(1); // not set
Hello h3(freeFunction); // custom function
h1.myfunction();
h2.myfunction();
h3.myfunction();
}
prints:
Default function called on 0x7fffa12518e0
myfunctionimpl not set!
freeFunction
So here the member function myfunction behaves the same way for every instance; calls the myfunctionimpl function object (if it is set). But you can customise the function object that is called for each instance, since that is just class data.
The default constructor demonstrates use of lambdas, which allow you to write small functions in place, which is probably what you will want to do to provide custom behaviour when each object is constructed. There are lots of tutorials for lambdas, for instance.
No, a member function of all instances of the same class behave the same. However, the behaviour can depend on the state of the object. For example, you could store a function pointer in a data member and call the pointed function in the member function. So, the member function does exactly the same thing for each instance: calls the function pointed by the member, but the observed behaviour may be completely different if the pointed function is different.
Also, if the function is virtual, then instances of different subclasses can override the virtual function differently.
As from your comment
I am trying to create a kind of framework using c++ and opengl. Suppose i have a object of a class lets say Button which has a function onClick. On clicking button different users should be able to define the function in their own way.
See here for an excellent article by Herb Sutter on the subject of virtuality, since that is what you would look for when considering to build functionality described in your question and building framework.
The questions are old, but people still keep asking them,
One building framework could be interested on
Polymorphism pointers and class inheritance;
Virtual functions a member functions whose behavior can be overridden in derived classes.
Ok so often times I have seen the following type of event handling used:
Connect(objectToUse, MyClass::MyMemberFunction);
for some sort of event handling where objectToUse is of the type MyClass. My question is how exactly this works. How would you convert this to something that would do objectToUse->MyMemberFunction()
Does the MyClass::MyMemberFunction give an offset from the beginning of the class that can then be used as a function pointer?
In addition to Mats' answer, I'll give you a short example of how you can use a non-static member function in this type of thing. If you're not familiar with pointers to member functions, you may want to check out the FAQ first.
Then, consider this (rather simplistic) example:
class MyClass
{
public:
int Mult(int x)
{
return (x * x);
}
int Add(int x)
{
return (x + x);
}
};
int Invoke(MyClass *obj, int (MyClass::*f)(int), int x)
{ // invokes a member function of MyClass that accepts an int and returns an int
// on the object 'obj' and returns.
return obj->*f(x);
}
int main(int, char **)
{
MyClass x;
int nine = Invoke(&x, MyClass::Mult, 3);
int six = Invoke(&x, MyClass::Add, 3);
std::cout << "nine = " << nine << std::endl;
std::cout << "six = " << six << std::endl;
return 0;
}
Typically, this uses a static member function (that takes a pointer as an argument), in which case the the objectToUse is passed in as a parameter, and the MyMemberFunction would use objectToUse to set up a pointer to a MyClass object and use that to refer to member variables and member functions.
In this case Connect will contain something like this:
void Connect(void *objectToUse, void (*f)(void *obj))
{
...
f(objectToUse);
...
}
[It is also quite possible that f and objectToUse are saved away somewhere to be used later, rather than actually inside Connnect, but the call would look the same in that case too - just from some other function called as a consequence of the event that this function is supposed to be called for].
It's also POSSIBLE to use a pointer to member function, but it's quite complex, and not at all easy to "get right" - both when it comes to syntax and "when and how you can use it correctly". See more here.
In this case, Connect would look somewhat like this:
void Connect(MyClass *objectToUse, void (Myclass::*f)())
{
...
objectToUse->*f();
...
}
It is highly likely that templates are used, as if the "MyClass" is known in the Connect class, it would be pretty pointless to have a function pointer. A virtual function would be a much better choice.
Given the right circumstances, you can also use virtual functions as member function pointers, but it requires the compiler/environment to "play along". Here's some more details on that subject [which I've got no personal experience at all of: Pointers to virtual member functions. How does it work?
Vlad also points out Functors, which is an object wrapping a function, allowing for an object with a specific behaviour to be passed in as a "function object". Typically this involves a predefined member function or an operatorXX which is called as part of the processing in the function that needs to call back into the code.
C++11 allows for "Lambda functions", which is functions declared on the fly in the code, that doesn't have a name. This is something I haven't used at all, so I can't really comment further on this - I've read about it, but not had a need to use it in my (hobby) programming - most of my working life is with C, rather than C++ although I have worked for 5 years with C++ too.
I might be wrong here, but as far as I understand,
In C++, functions with the same signature are equal.
C++ member functions with n parameters are actually normal functions with n+1 parameters. In other words, void MyClass::Method( int i ) is in effect void (some type)function( MyClass *ptr, int i).
So therefore, I think the way Connect would work behind the scenes is to cast the member method signature to a normal function signature. It would also need a pointer to the instance to actually make the connection work, which is why it would need objectToUse
In other words, it would essentially be using pointers to functions and casting them to a more generic type until it can be called with the parameters supplied and the additional parameter, which is the pointer to the instance of the object
If the method is static, then a pointer to an instance doesn't make sense and its a straight type conversion. I have not figured out the intricacies involved with non-static methods yet - a look at the internals of boost::bind is probably what you want to do to understand that :) Here is how it would work for a static function.
#include <iostream>
#include <string>
void sayhi( std::string const& str )
{
std::cout<<"function says hi "<<str<<"\n";
}
struct A
{
static void sayhi( std::string const& str )
{
std::cout<<"A says hi "<<str<<"\n";
}
};
int main()
{
typedef void (*funptr)(std::string const&);
funptr hello = sayhi;
hello("you"); //function says...
hello = (&A::sayhi); //This is how Connect would work with a static method
hello("you"); //A says...
return 0;
}
For event handling or callbacks, they usually take two parameters - a callback function and a userdata argument. The callback function's signature would have userdata as one of the parameters.
The code which invokes the event or callback would invoke the function directly with the userdata argument. Something like this for example:
eventCallbackFunction(userData);
In your event handling or callback function, you can choose to use the userdata to do anything you would like.
Since the function needs to be callable directly without an object, it can either be a global function or a static method of a class (which does not need an object pointer).
A static method has limitations that it can only access static member variables and call other static methods (since it does not have the this pointer). That is where userData can be used to get the object pointer.
With all this mind, take a look at the following example code snippet:
class MyClass
{
...
public:
static MyStaticMethod(void* userData)
{
// You can access only static members here
MyClass* myObj = (MyClass*)userdata;
myObj->MyMemberMethod();
}
void MyMemberMethod()
{
// Access any non-static members here as well
...
}
...
...
};
MyClass myObject;
Connect(myObject, MyClass::MyStaticMethod);
As you can see you can access even member variables and methods as part of the event handling if you could make a static method which would be invoked first which would chain the call to a member method using the object pointer (retrieved from userData).
When implementing polymorphic behavior in C++ one can either use a pure virtual method or one can use function pointers (or functors). For example an asynchronous callback can be implemented by:
Approach 1
class Callback
{
public:
Callback();
~Callback();
void go();
protected:
virtual void doGo() = 0;
};
//Constructor and Destructor
void Callback::go()
{
doGo();
}
So to use the callback here, you would need to override the doGo() method to call whatever function you want
Approach 2
typedef void (CallbackFunction*)(void*)
class Callback
{
public:
Callback(CallbackFunction* func, void* param);
~Callback();
void go();
private:
CallbackFunction* iFunc;
void* iParam;
};
Callback::Callback(CallbackFunction* func, void* param) :
iFunc(func),
iParam(param)
{}
//Destructor
void go()
{
(*iFunc)(iParam);
}
To use the callback method here you will need to create a function pointer to be called by the Callback object.
Approach 3
[This was added to the question by me (Andreas); it wasn't written by the original poster]
template <typename T>
class Callback
{
public:
Callback() {}
~Callback() {}
void go() {
T t; t();
}
};
class CallbackTest
{
public:
void operator()() { cout << "Test"; }
};
int main()
{
Callback<CallbackTest> test;
test.go();
}
What are the advantages and disadvantages of each implementation?
Approach 1 (Virtual Function)
"+" The "correct way to do it in C++
"-" A new class must be created per callback
"-" Performance-wise an additional dereference through VF-Table compared to Function Pointer. Two indirect references compared to Functor solution.
Approach 2 (Class with Function Pointer)
"+" Can wrap a C-style function for C++ Callback Class
"+" Callback function can be changed after callback object is created
"-" Requires an indirect call. May be slower than functor method for callbacks that can be statically computed at compile-time.
Approach 3 (Class calling T functor)
"+" Possibly the fastest way to do it. No indirect call overhead and may be inlined completely.
"-" Requires an additional Functor class to be defined.
"-" Requires that callback is statically declared at compile-time.
FWIW, Function Pointers are not the same as Functors. Functors (in C++) are classes that are used to provide a function call which is typically operator().
Here is an example functor as well as a template function which utilizes a functor argument:
class TFunctor
{
public:
void operator()(const char *charstring)
{
printf(charstring);
}
};
template<class T> void CallFunctor(T& functor_arg,const char *charstring)
{
functor_arg(charstring);
};
int main()
{
TFunctor foo;
CallFunctor(foo,"hello world\n");
}
From a performance perspective, Virtual functions and Function Pointers both result in an indirect function call (i.e. through a register) although virtual functions require an additional load of the VFTABLE pointer prior to loading the function pointer. Using Functors (with a non-virtual call) as a callback are the highest performing method to use a parameter to template functions because they can be inlined and even if not inlined, do not generate an indirect call.
Approach 1
Easier to read and understand
Less possibility of errors (iFunc cannot be NULL, you're not using a void *iParam, etc
C++ programmers will tell you that this is the "right" way to do it in C++
Approach 2
Slightly less typing to do
VERY slightly faster (calling a virtual method has some overhead, usually the same of two simple arithmetic operations.. So it most likely won't matter)
That's how you would do it in C
Approach 3
Probably the best way to do it when possible. It will have the best performance, it will be type safe, and it's easy to understand (it's the method used by the STL).
The primary problem with Approach 2 is that it simply doesn't scale. Consider the equivalent for 100 functions:
class MahClass {
// 100 pointers of various types
public:
MahClass() { // set all 100 pointers }
MahClass(const MahClass& other) {
// copy all 100 function pointers
}
};
The size of MahClass has ballooned, and the time to construct it has also significantly increased. Virtual functions, however, are O(1) increase in the size of the class and the time to construct it- not to mention that you, the user, must write all the callbacks for all the derived classes manually which adjust the pointer to become a pointer to derived, and must specify function pointer types and what a mess. Not to mention the idea that you might forget one, or set it to NULL or something equally stupid but totally going to happen because you're writing 30 classes this way and violating DRY like a parasitic wasp violates a caterpillar.
Approach 3 is only usable when the desired callback is statically knowable.
This leaves Approach 1 as the only usable approach when dynamic method invocation is required.
It's not clear from your example if you're creating a utility class or not. Is you Callback class intended to implement a closure or a more substantial object that you just didn't flesh out?
The first form:
Is easier to read and understand,
Is far easier to extend: try adding methods pause, resume and stop.
Is better at handling encapsulation (presuming doGo is defined in the class).
Is probably a better abstraction, so easier to maintain.
The second form:
Can be used with different methods for doGo, so it's more than just polymorphic.
Could allow (with additional methods) changing the doGo method at run-time, allowing the instances of the object to mutate their functionality after creation.
Ultimately, IMO, the first form is better for all normal cases. The second has some interesting capabilities, though -- but not ones you'll need often.
One major advantage of the first method is it has more type safety. The second method uses a void * for iParam so the compiler will not be able to diagnose type problems.
A minor advantage of the second method is that it would be less work to integrate with C. But if you're code base is only C++, this advantage is moot.
Function pointers are more C-style I would say. Mainly because in order to use them you usually must define a flat function with the same exact signature as your pointer definition.
When I write C++ the only flat function I write is int main(). Everything else is a class object. Out of the two choices I would choose to define an class and override your virtual, but if all you want is to notify some code that some action happened in your class, neither of these choices would be the best solution.
I am unaware of your exact situation but you might want to peruse design patterns
I would suggest the observer pattern. It is what I use when I need to monitor a class or wait for some sort of notification.
For example, let us look at an interface for adding read functionality to a class:
struct Read_Via_Inheritance
{
virtual void read_members(void) = 0;
};
Any time I want to add another source of reading, I have to inherit from the class and add a specific method:
struct Read_Inherited_From_Cin
: public Read_Via_Inheritance
{
void read_members(void)
{
cin >> member;
}
};
If I want to read from a file, database, or USB, this requires 3 more separate classes. The combinations start to be come very ugly with multiple objects and multiple sources.
If I use a functor, which happens to resemble the Visitor design pattern:
struct Reader_Visitor_Interface
{
virtual void read(unsigned int& member) = 0;
virtual void read(std::string& member) = 0;
};
struct Read_Client
{
void read_members(Reader_Interface & reader)
{
reader.read(x);
reader.read(text);
return;
}
unsigned int x;
std::string& text;
};
With the above foundation, objects can read from different sources just by supplying different readers to the read_members method:
struct Read_From_Cin
: Reader_Visitor_Interface
{
void read(unsigned int& value)
{
cin>>value;
}
void read(std::string& value)
{
getline(cin, value);
}
};
I don't have to change any of the object's code (a good thing because it is already working). I can also apply the reader to other objects.
Generally, I use inheritance when I am performing generic programming. For example, if I have a Field class, then I can create Field_Boolean, Field_Text and Field_Integer. In can put pointers to their instances into a vector<Field *> and call it a record. The record can perform generic operations on the fields, and doesn't care or know what kind of a field is processed.
Change to pure virtual, first off. Then inline it. That should negate any method overhead call at all, so long as inlining doesn't fail (and it won't if you force it).
May as well use C, because this is the only real useful major feature of C++ compared to C. You will always call method and it can't be inlined, so it will be less efficient.