Metal Cat
Metal Cat

Reputation: 95

how to use function as variable c++

I want to create somekind of event system in c++ for my needs

I know that you can use fuction as other function parameter

May be i missed something(But in c# you can do it with events handlers)

Upvotes: 4

Views: 18671

Answers (2)

tangoal
tangoal

Reputation: 769

You can use the "Observer Pattern" (see also UML):

Every event listener must be derived from an abstract class (Observer), which contains the event methods. You can implement your specific event listener code in such a derived class. A Subject class contains all the event listener objects (a vector of abstract class Observer) and notifies them in case the event occurs.

Upvotes: 2

Hepic Hepic
Hepic Hepic

Reputation: 132

You can store it in a pointer. For example

void func(int a) { ... }
void (*ptr)(int) = &func;
(*ptr)(5); // call the function with value 5

ptr is a pointer which takes as value a memory of a function that has one 'int' argument and 'void' as return type.

Upvotes: 11

Related Questions