Home > OS >  Define a different function for each instance of a class
Define a different function for each instance of a class

Time:05-21

Say I have this class:

class Object {
  public:
    int x;
    int y;

    void update(SDL_Event);
    void start();
};

I want to be able to make start and update change behavior from instance to instance.

I have tried using function pointers, like so:

class Object {
  public:
    int x;
    int y;

    void (*update)(SDL_Event);
    void (*start)(void);
};

void teststart() {
  x  ;
  return;
}

And in my main(), I do:

testlevel.objs[1].start = teststart;

But then, I cannot reference variables from inside the class.

I am sure there is something obvious I am overlooking, but searching online yields no results for when the pointer is in the class.

Maybe function pointers are not the right answer?

CodePudding user response:

You would need to pass your functions a pointer/reference to the Object instance, eg:

class Object {
  public:
    int x;
    int y;

    void (*doupdate)(Object*, SDL_Event);
    void (*dostart)(Object*);

    void update(SDL_Event event) { if (doupdate) doupdate(this, event); } 
    void start() { if (dostart) dostart(this); }
};
void teststart(Object* obj) {
  obj->x  ;
}

void testupdate(Object* obj, SDL_Event event) {
  // update obj as needed...
}

Object &obj = testlevel.objs[1];
obj.dostart = teststart;
obj.doupdate = testupdate;

Otherwise, use std::function with capturing lambdas instead:

#include <functional>

class Object {
  public:
    int x;
    int y;

    std::function<void(SDL_Event)> update;
    std::function<void()> start;
};
Object *obj = &(testlevel.objs[1]);

obj->start = [obj](){
  obj->x  ;
};

obj->update = [obj](SDL_Event event){
  // update obj as needed...
};
  • Related