Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class member function as Callback

Tags:

c++

callback

In PortAudio's C++ bindings, there is a MemFunCallBackStream constructior that can be called as:

portaudio::MemFunCallbackStream<MyClass> streamRecord(paramsRecord, 
                                                     *AnInstanceOfMyClass,
                                                     &MyClass::MemberFunction);

where last parameter is the callback function. However without using the & operator on that parameter compiler fails. But as far as I know & parameter is omitable when obtaining address of functions to use in function pointers. Is this somehow different from C callback function and ptr. to func. syntax?

like image 925
paul simmons Avatar asked Aug 13 '10 10:08

paul simmons


People also ask

How do you call a class member function?

A member function is declared and defined in the class and called using the object of the class. A member function is declared in the class but defined outside the class and is called using the object of the class.

How do you implement a callback in C++?

In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function. In C, a callback function is a function that is called through a function pointer. In C++ STL, functors are also used for this purpose.

Is class member and member function same?

Member functions are operators and functions that are declared as members of a class. Member functions do not include operators and functions declared with the friend specifier. These are called friends of a class. You can declare a member function as static ; this is called a static member function.

How do you assign a callback function?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.


1 Answers

This FAQ seems to suggest that you can omit the & (for static member functions, at least), but then goes on to give various reasons why you shouldn't confuse ordinary function-pointers with C++ member-function-pointers.

EDIT: Found more information here, which is relevant to non-static member functions:

Some compilers (most notably MSVC 6 and 7) will let you omit the &, even though it is non-standard and confusing. More standard-compliant compilers (e.g., GNU G++ and MSVC 8 (a.k.a. VS 2005)) require it, so you should definitely put it in. To invoke the member function pointer, you need to provide an instance of SomeClass, and you must use the special operator ->*. This operator has a low precedence, so you need to put it in parentheses. [Emphasis added]

like image 145
David Avatar answered Oct 28 '22 12:10

David