C++ function pointer in class ? - Page 1
Forum section: electronics / general

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 04, 2018, 01:56:47 pm
content: Hi, what should i type to get a function pointer pointing to a function from a class ?thanks in advance

author: zzattack
author_rank: Regular Contributor
timestamp: May 04, 2018, 02:17:21 pm
content: One hint: you need to differentiate between static and non-static functions.Try to find out what type is assigned to an 'auto' variable when setting it to a member function.

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 04, 2018, 02:56:21 pm
content: I totally dont understand.

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 04, 2018, 03:09:40 pm
content: Look i make a code example what dont works :Code:class Test{public:Test::Test(){Run = Func1;}void (*Run)();void Func1(){};void Func2(){};};Test*test = NULL;Test*test2 = NULL;test = new Test();test2 = new Test();

author: Mechatrommer
author_rank: Super Contributor
timestamp: May 04, 2018, 03:12:41 pm
content: https://stackoverflow.com/questions/1485983/calling-c-class-methods-via-a-function-pointer

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 04, 2018, 03:44:24 pm
content: Thanks, i know i can read the internet,they all give other solution, and in the end i need some external files also, like boost, i dont want to use external files.Wich is the good answer then ?

author: andersm
author_rank: Super Contributor
timestamp: May 04, 2018, 06:30:26 pm
content: See eg.std::mem_fn, orstd::function.

author: hans
author_rank: Super Contributor
timestamp: May 04, 2018, 07:00:19 pm
content: Function pointers are not so easy as in C, because classes can have a specific context, such as which instance is the function call bound to? (what is the value of "this")But also if the function is virtual it becomes non-trivial.The std library functions referenced by andersm are what you're looking for, but note that the standard STL will probably use memory allocation which makes the binaries on embedded explode wrt code size, heap usage, etc.

author: nctnico
author_rank: Super Contributor
timestamp: May 04, 2018, 07:01:02 pm
content: A class is already a collection of function pointers so I don't understand why you would want to call a function from a class without the class itself.With static functions you can do: class_name::function_name() but for any other function it will need to be called using the class.Your example looks like C style polymorphism (OO in plain C). I wouldn't do it that way because in C++ that is allready available under the hood.All in all: please try to explain the problem you are trying to solve.

author: MosherIV
author_rank: Super Contributor
timestamp: May 04, 2018, 07:45:28 pm
content: QuoteAgreedTo put it another way, you are NOT thinking OO, you are still thinking 'how do I call a function with this data'In OO you get the object itself to do whatever it needs to do.In practicle terms, one object (which knows about the other) calls the other objects public function, the other object should know what data (inside the object) to process.(Do not worry, it took me 5 years to make the paradime shift)

author: gf
author_rank: Super Contributor
timestamp: May 04, 2018, 08:02:31 pm
content: I guess you are asking for member function pointers.Seehttp://en.cppreference.com/w/cpp/language/pointerScroll down to the section "Pointers to member functions" on this page.

author: ataradov
author_rank: Super Contributor
timestamp: May 04, 2018, 08:34:39 pm
content: The reason you are not finding good answers is because there are none. C++ is stupid this way and there is not much you can do about it. There is a number of known workarounds, but they all are ugly.

author: NorthGuy
author_rank: Super Contributor
timestamp: May 04, 2018, 08:36:19 pm
content: Quote from: JanJansen on May 04, 2018, 03:44:24 pmNon-static member functions are not exactly the functions you declare. They have an additional hidden parameter which points to the instance of the object. So, it is entirely impossible to call such a function without knowing which object it belongs to. Therefore, the pointer to the function is totally useless outside of the object.

author: gf
author_rank: Super Contributor
timestamp: May 04, 2018, 09:49:48 pm
content: QuoteLiterally you asked for a "function pointer in class", and "pointers to member functions" do indeed exist in the C++ language. The question is, whether you really want a member function pointer, or whether you actually want some kind of closure instead, do you?If you want the latter, then the C++ language and standard libary offer constructs like lambda functions, std::bind, or std::function (if you also need type erasure). Particulary std::function may be a bit expensive, though (reagarding overhead).Alternatively you can implement your own "function pointer" class, providing a call operator, and internally storing everything you need for the invocation, e.g. a pointer to an object, a pointer to a member function of the object's class, and maybe also some arguments that need to be passed to the member function.

author: andyturk
author_rank: Frequent Contributor
timestamp: May 05, 2018, 02:47:57 am
content: Quote from: JanJansen on May 04, 2018, 01:56:47 pmPointers to member functions in C++ are weird. You should probably look for another way to write your code.However, under the hood, C++ implicitly passes a pointer to the instance as the first argument. You don't see this in the source code, but the compiler adds that extra argument to the generated assembly. Back in the days when C++ was actually a source-to-source translator, you would be able to see the extra argument in the generated code.Anyway, it's often possible to "trick" the system into giving you a regular C-style function that accepts a pointer to the instance as its first argument. This is useful when you're interfacing with "object oriented" C code that uses the same convention. It's not standard C++, but with GCC you can specify acompile-time switchto turn off errors related to this.https://godbolt.org/g/onVjK1

author: amyk
author_rank: Super Contributor
timestamp: May 05, 2018, 03:57:17 am
content: Yes, "member function pointer" is the "official" way, but if you do not like the syntax and still need to call the function with a class, you can pass that "this" parameter yourself.

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 05, 2018, 12:16:26 pm
content: Thanks for all replys.Why do i want it : to save a switch for multiple states in the class.I dont use STD stuff at all, for linked list i program it myself also, i dont like std at all.So you say C++ has it under the hood already, is what you suggest make another class and use virtual functions ?, no i dont want to create more classes,or what is it ?Offcourse i dont want to use any static at all, every class is on its own.I,m making games : and want by example 1 projectile class wich has homing and normal fire, and enemys with more states.Thing is in gameland the competition is high, and they only brag and promote themselfs and wont help anyone.

author: andyturk
author_rank: Frequent Contributor
timestamp: May 05, 2018, 01:28:20 pm
content: Quote from: JanJansen on May 05, 2018, 12:16:26 pmBy "save a switch" do you mean eliminate a switch? Or maybe evaluate a switch once and save the result which can be called many times?In any event, compilers are pretty smart these days about compiling switch statements. Depending on the range of case values, it might create an efficient lookup table (depending on optimization level). So if you're just looking at pointers-to-members as an optimization strategy, it may not get you a lot.

author: gf
author_rank: Super Contributor
timestamp: May 05, 2018, 01:37:21 pm
content: QuoteAnd each of the states is represented by a function, right?Maybe something like this?Code:class projectile {public:// the member function ponter variable "state"void (projectile::* state)();// initialize state in constructorprojectile() : state(&projectile::homing) {}void homing() {...state = &projectile::normal_fire; // set a new state...}void normal_fire() {...state = &projectile::homing; // set a new state...}void f(){// call state from inside the class(this->*state)();}};Call from outside the class:Code:projectile* p = ...;(p->*p->state)();

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 05, 2018, 02:19:12 pm
content: Thanks GF, will try, i think you have a typo here btw : (p->*p->state)();Yes Andy, i am trying to eliminate a switch in loop, those big switches are very slow.I use this technique normally without classes, and its really helping to make things faster,not only faster, the programming is also very simple, have a seperate function for everything, ok there might be some code double typed, im not optimizing for space only for speed.

author: gf
author_rank: Super Contributor
timestamp: May 05, 2018, 02:46:56 pm
content: QuoteTo the best of my knowledge this is the correct syntax and not a typo.Note thatp->*statewould refer to a variablestatein the current scope and not to the member variablestatein the object pointed to byp.Still keep in mind, that C++ member function pointer are more complex than traditional static function pointers, leading to a higher overhead in the code generated by the compiler. The technical background and reason is IMO very well explained here:https://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-PossibleEDIT:If the code size and runtime overhead of member function pointers is an issue, then I'd introduce a static shadow function for each state function and use a traditional function pointer instead. If you compile with optimization so that the compiler inlines functions, then the static functions won't introduce any overhead in the genrated binary.Code:class projectile {public:void (*state_)(projectile*);projectile() : state_(homing) {}void state(){state_(this);}// functions for eaach statevoid homing() {state_ = normal_fire; // set a new state}void normal_fire() {state_ = homing; // set a new state}// static shadow functions for each statestatic void homing(projectile *p) {p->homing();}static void normal_fire(projectile *p) {p->normal_fire();}};Call from outside:Code:projectile* p = ...;p->state();

author: NorthGuy
author_rank: Super Contributor
timestamp: May 05, 2018, 04:18:26 pm
content: If you want a C++ equivalent of the state machine where states are represented by a pointer to a function, then one way to accomplish this is to use pointers to objects as this:- each state of the state machine is represented by an instance of an object- each object is inherited from common ancestor which implements a basic set of functions- each object has a "process()" virtual function which is called by the state machine. Since objects are polymorphic, you can create different classes of the objects to process different states- assigning the pointer object as a state of the state machine automatically makes the object'sprocess() function the processor for the current state- objects may have different virtual function besides "process()", for example functions to handlespecial conditions, errors etc. which may enrich the state machine.- objects may have their own variables to implement things such as counters- objects can be dynamically created (or destroyed), so the set of states can change at run timeIt is certainly lot more text to write compared to C, but this is the C++ way.

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 05, 2018, 04:38:19 pm
content: Thanks Northguy, but indeed to much text, i try make things simpler not more complicated.I use your method for all game states btw.

author: MosherIV
author_rank: Super Contributor
timestamp: May 05, 2018, 06:05:04 pm
content: QuoteLike I said, you are not thinking in OO.To do the missile behaviour :Create interface/base missile class, add method Fire()Derive n classes from base missile class, one for homing and one for normal, etcCreate missile objects as neededWhat ever class/object has the missiles, creat a pointer or reference to the base class.Populate the holder class with missile object. Since you used pointers to classes, they can be changed as needed. Now the holder class just calls the pointer to base missile class->Fire()

author: JanJansen
author_rank: Frequent Contributor
timestamp: May 05, 2018, 06:15:24 pm
content: Ok your right about having multiple missile classes, i could do that.Now for endboss, it needs multiple states.And what if the rocket become homing at a certain point to have more spread.Anyways i gotto go now, i will read tomorow.

author: alanambrose
author_rank: Frequent Contributor
timestamp: May 12, 2018, 05:13:06 am
content: >>> Hi, what should i type to get a function pointer pointing to a function from a class ?Also check out 'functors'. I've used this technique extensively in the past e.g. for writing general purpose integration or optimisation algorithms that take the function to be integrated / optimised as a function represented as a functor.A.

author: Korken
author_rank: Regular Contributor
timestamp: May 13, 2018, 07:45:00 pm
content: If you want to call with "pointer to member function", I have made two helpers for that (and a bit more) which can be found here:https://github.com/korken89/esl/tree/master/src/esl/callableThey are made for non-dynamic allocation use, so the esl::function uses a fixed size buffer to store arguments, while esl::function_view does not allow for storing arguments.

author: Daixiwen
author_rank: Frequent Contributor
timestamp: May 14, 2018, 09:03:59 am
content: By the way I heard one day about this site which is great to find the syntax of complicated C statements, like function pointers:https://cdecl.org/C gibberish to English converterIt doesn't do C++ though.