Author Topic: C++ function pointer in class ?  (Read 4871 times)

0 Members and 1 Guest are viewing this topic.

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
C++ function pointer in class ?
« on: May 04, 2018, 01:56:47 pm »
Hi, what should i type to get a function pointer pointing to a function from a class ?
thanks in advance
aliexpress parachute
 

Offline zzattack

  • Regular Contributor
  • *
  • Posts: 126
  • Country: nl
Re: C++ function pointer in class ?
« Reply #1 on: May 04, 2018, 02:17:21 pm »
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.
 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #2 on: May 04, 2018, 02:56:21 pm »
I totally dont understand.
aliexpress parachute
 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #3 on: May 04, 2018, 03:09:40 pm »
Look i make a code example what dont works :

Code: [Select]
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();

aliexpress parachute
 

Offline Mechatrommer

  • Super Contributor
  • ***
  • Posts: 11631
  • Country: my
  • reassessing directives...
Nature: Evolution and the Illusion of Randomness (Stephen L. Talbott): Its now indisputable that... organisms “expertise” contextualizes its genome, and its nonsense to say that these powers are under the control of the genome being contextualized - Barbara McClintock
 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #5 on: May 04, 2018, 03:44:24 pm »
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 ?
aliexpress parachute
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1198
  • Country: fi
Re: C++ function pointer in class ?
« Reply #6 on: May 04, 2018, 06:30:26 pm »

Offline hans

  • Super Contributor
  • ***
  • Posts: 1638
  • Country: nl
Re: C++ function pointer in class ?
« Reply #7 on: May 04, 2018, 07:00:19 pm »
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.
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
Re: C++ function pointer in class ?
« Reply #8 on: May 04, 2018, 07:01:02 pm »
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.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline MosherIV

  • Super Contributor
  • ***
  • Posts: 1530
  • Country: gb
Re: C++ function pointer in class ?
« Reply #9 on: May 04, 2018, 07:45:28 pm »
Quote
so I don't understand why you would want to call a function from a class without the class itself.
Agreed  :)

To 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)
 

Online gf

  • Super Contributor
  • ***
  • Posts: 1170
  • Country: de
Re: C++ function pointer in class ?
« Reply #10 on: May 04, 2018, 08:02:31 pm »
I guess you are asking for member function pointers.
See http://en.cppreference.com/w/cpp/language/pointer
Scroll down to the section "Pointers to member functions" on this page.
 

Offline ataradov

  • Super Contributor
  • ***
  • Posts: 11258
  • Country: us
    • Personal site
Re: C++ function pointer in class ?
« Reply #11 on: May 04, 2018, 08:34:39 pm »
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.
Alex
 

Offline NorthGuy

  • Super Contributor
  • ***
  • Posts: 3146
  • Country: ca
Re: C++ function pointer in class ?
« Reply #12 on: May 04, 2018, 08:36:19 pm »
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 ?

Non-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.
 

Online gf

  • Super Contributor
  • ***
  • Posts: 1170
  • Country: de
Re: C++ function pointer in class ?
« Reply #13 on: May 04, 2018, 09:49:48 pm »
Quote
Wich is the good answer then ?

Literally 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.

 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: C++ function pointer in class ?
« Reply #14 on: May 05, 2018, 02:47:57 am »
Hi, what should i type to get a function pointer pointing to a function from a class ?
thanks in advance
Pointers 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 a compile-time switch to turn off errors related to this.

https://godbolt.org/g/onVjK1
 

Offline amyk

  • Super Contributor
  • ***
  • Posts: 8275
Re: C++ function pointer in class ?
« Reply #15 on: May 05, 2018, 03:57:17 am »
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.
 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #16 on: May 05, 2018, 12:16:26 pm »
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.
aliexpress parachute
 

Offline andyturk

  • Frequent Contributor
  • **
  • Posts: 895
  • Country: us
Re: C++ function pointer in class ?
« Reply #17 on: May 05, 2018, 01:28:20 pm »
Why do i want it : to save a switch for multiple states in the class.
By "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.
 

Online gf

  • Super Contributor
  • ***
  • Posts: 1170
  • Country: de
Re: C++ function pointer in class ?
« Reply #18 on: May 05, 2018, 01:37:21 pm »
Quote
Why do i want it : to save a switch for multiple states in the class.

And each of the states is represented by a function, right?

Maybe something like this?

Code: [Select]
class projectile {
public:
    // the member function ponter variable "state"
    void (projectile::* state)();

    // initialize state in constructor
    projectile() : 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: [Select]
projectile* p = ...;
(p->*p->state)();
 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #19 on: May 05, 2018, 02:19:12 pm »
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.
aliexpress parachute
 

Online gf

  • Super Contributor
  • ***
  • Posts: 1170
  • Country: de
Re: C++ function pointer in class ?
« Reply #20 on: May 05, 2018, 02:46:56 pm »
Quote
Thanks GF, will try, i think you have a typo here btw : (p->*p->state)();

To the best of my knowledge this is the correct syntax and not a typo.

Note that p->*state would refer to a variable state in the current scope and not to the member variable state in the object pointed to by p.

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-Possible

EDIT:

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: [Select]
class projectile {
public:
    void (*state_)(projectile*);

    projectile() : state_(homing) {}

    void state()
    {
        state_(this);
    }

    // functions for eaach state

    void homing() {
        state_ = normal_fire;  // set a new state
    }

    void normal_fire() {
        state_ = homing;  // set a new state
    }

    // static shadow functions for each state

    static void homing(projectile *p) {
        p->homing();
    }

    static void normal_fire(projectile *p) {
        p->normal_fire();
    }
};

Call from outside:

Code: [Select]
projectile* p = ...;
p->state();
« Last Edit: May 05, 2018, 03:40:03 pm by gf »
 

Offline NorthGuy

  • Super Contributor
  • ***
  • Posts: 3146
  • Country: ca
Re: C++ function pointer in class ?
« Reply #21 on: May 05, 2018, 04:18:26 pm »
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's
process() function the processor for the current state
- objects may have different virtual function besides "process()", for example functions to handle
special 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 time

It is certainly lot more text to write compared to C, but this is the C++ way.

 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #22 on: May 05, 2018, 04:38:19 pm »
Thanks Northguy, but indeed to much text, i try make things simpler not more complicated.
I use your method for all game states btw.
aliexpress parachute
 

Offline MosherIV

  • Super Contributor
  • ***
  • Posts: 1530
  • Country: gb
Re: C++ function pointer in class ?
« Reply #23 on: May 05, 2018, 06:05:04 pm »
Quote
Why do i want it : to save a switch for multiple states in the class.

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.
Like 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, etc
Create missile objects as needed
What 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()
« Last Edit: May 05, 2018, 06:22:37 pm by MosherIV »
 

Offline JanJansenTopic starter

  • Frequent Contributor
  • **
  • Posts: 380
  • Country: nl
Re: C++ function pointer in class ?
« Reply #24 on: May 05, 2018, 06:15:24 pm »
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.
aliexpress parachute
 

Offline alanambrose

  • Frequent Contributor
  • **
  • Posts: 377
  • Country: gb
Re: C++ function pointer in class ?
« Reply #25 on: May 12, 2018, 05:13:06 am »
>>> 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.
“A foolish consistency is the hobgoblin of little minds"
 

Offline Korken

  • Regular Contributor
  • *
  • Posts: 84
  • Country: se
Re: C++ function pointer in class ?
« Reply #26 on: May 13, 2018, 07:45:00 pm »
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/callable
They 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.
 

Offline Daixiwen

  • Frequent Contributor
  • **
  • Posts: 352
  • Country: no
Re: C++ function pointer in class ?
« Reply #27 on: May 14, 2018, 09:03:59 am »
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 converter
It doesn't do C++ though.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf