-2

I'm trying to set a pointer to a member function from another class, but I can't figure out how to do this. I have three classes: Control, Button, Textbox. Button and Textbox have their own void _Draw(), and the Control class has a pointer to void (*drawFunc(int))

I want both Button and Textbox classes having access to Control _drawFunc pointer to set it as their _Draw functions.

void Draw1(int t) { 
    printf("%d\n", t);
}

struct Control {
    void (*drawFunc)(int);

    Control() {}
};

struct Button : Control{

    void _Draw(int m) {
        // ... 
    }

    Button() {
        drawFunc = &Button::_Draw; // Draw1 works fine
    }

};

struct Textbox : Control{

    void _Draw(int m) {
        // ... 
    }

    Textbox() {
        drawFunc = &Textbox::_Draw; // Draw1 works fine
    }

};
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
SJBur
  • 35
  • 3
  • 15
  • 1
    `void (*drawFunc)(int)` is NOT a pointer-to-member-function. It is a pointer to a regular (freestanding) function. Member functions and regular functions are beasts of completely different nature. You can't make `drawFunc` to point to `Button::_Draw`. – AnT stands with Russia Aug 04 '17 at 17:18
  • Pointers to functions and pointers to member functions are different types. – François Andrieux Aug 04 '17 at 17:19
  • 1
    Also note that names starting with an `_` followed by an `A-Z` are reserved and shouldn't be used. – HolyBlackCat Aug 04 '17 at 17:23
  • 1
    ^ Not just shouldn't, mustn't! – Baum mit Augen Aug 04 '17 at 17:24
  • @SJBar -- If you think about this a bit, how would you have made the call to that member function using regular pointer-to-function call syntax? To call a non-static member function normally, you need an object, i.e. `object.foo()` or `object->foo()`. So how do you fit `object` into the pointer-to-function call syntax you are familiar with? That's right, you can't -- different beasts, as stated previously. – PaulMcKenzie Aug 04 '17 at 17:32

1 Answers1

0

You could use function<void(int)> drawFunc instead of void (drawFunc*)(int) and assign it with [this](int i) { this->_Draw(m); } to bind this or you make it static (which does not make sense), but for such problems there are virtual methods:

struct Control {
    virtual void draw(int) = 0;

    Control() {};
    virtual ~Control() {};
};

struct Button : public Control {
    void draw(int m) final override { // final is optional: if there are no subclasses of buttons
        // ...
    };
};
cmdLP
  • 1,658
  • 9
  • 19