How do function pointers work?

I am asking a few specific questions.

  • How can I initialize them in a class?
  • How to pass a function as an argument?
  • Should function pointers in a class be declared and defined?

For question number 2, here is what I mean:

void s(void) { //... } void f(function) { // what should I put as type to pass a function as an argument //... } f(s); 
+8
c ++ c pointers function-pointers
source share
4 answers

To define a function pointer, use the following syntax:

 return_type (*ref_name) (type args, ...) 

So, to define a reference to a function called "doSomething" that returns an int and takes an int argument, you should write this:

 int (*doSomething)(int number); 

Then you can assign a link to the actual function as follows:

 int someFunction(int argument) { printf("%i", argument); } doSomething = &someFunction; 

After that, you can call it directly:

 doSomething(5); //prints 5 

Because function pointers are essentially just pointers, you can really use them as instance variables in your classes.

When accepting function pointers as arguments, I prefer to use typedef instead of using cluttered syntax in the function prototype:

 typedef int (*FunctionAcceptingAndReturningInt)(int argument); 

Then you can use this new type as the argument type for the function:

 void invokeFunction(int func_argument, FunctionAcceptingAndReturningInt func) { int result = func(func_argument); printf("%i", result); } int timesFive(int arg) { return arg * 5; } invokeFunction(10, &timesFive); //prints 50 
+24
source share

this is not a strict answer, but to include custom / assigned code as a member of the class, I would mention using the / struct class with the () operator. For example:

 struct mycode { int k; mycode(int k_) : k(k_) { } int operator()(int x) { return x*k; } }; class Foo { public : Foo(int k) : f(k) {} public : mycode f; }; 

You can do:

 Foo code(5); std::cout << code.f(2) << std::endl; 

he will print "10", he wrote everything fine.

+2
source share

You should declare f as follows:

 void f(void (*x)()) { x(); // call the function that you pass as parameter (Ex. s()). } 

here is a great tutorial on function pointers and callbacks.

+1
source share

To answer the third question, you do not need to declare it in the classroom. But not for cross-border encapsulation, I usually prefer function pointers or functors, which pointers are again members of classes. The above examples are C-style function pointers, with the exception of Luis G. Costantini R. You can take a look at this to approach member function pointers. The keys of a C-style function are usually considered, for example, callback mechanisms, where there is a C code that you receive asynchronous messages. In such cases, there are no options, not declarations of handler methods in the global scope.

0
source share

Source: https://habr.com/ru/post/650431/


All Articles