Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define a function for a single instance of a class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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...
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading