0

The code is pretty straigh-forward. The code works if there isn't IDumb and I pass dumbClass directly to dumbWin. But when dumbClass has IDumb interface, the code crashes at print().

using namespace std;

class IDumb {
public :
virtual void print() = 0;
};

class dumbClass : public IDumb {
public :
void print() {
    cout << "this is dumb class" << endl;
}
};

class dumbWin : public Fl_Window {
IDumb *dc;
public:
dumbWin(IDumb *dc) : Fl_Window(100, 100, "win") {
    Fl_Button *b = new Fl_Button(10, 10, 50, 25, "OK");
    b->callback((Fl_Callback*)callbk, this);
    end();

    this->dc = dc;
}

void print() {
    dc->print();
}

static void callbk(void *p) {
    cout << "OK" << endl;
    ((dumbWin*)p)->print();
}
};

int main(int argc, char **argv)
{
IDumb *dC = new dumbClass();
dumbWin *dW = new dumbWin(dC);
dW->show();

return Fl::run();
}
harsh
  • 905
  • 1
  • 10
  • 21

1 Answers1

1

You call call b->callback before setting this->dc. Would that be a problem? You're better off with member initialization:

dumbWin(IDumb *dc) : Fl_Window(100, 100, "win"), dc(dc) 

Also, provide a virtual destructor for IDumb.

  • Didn't work. If I call `dc->print()` in constructor of `dumbWin` it works. Only when I call it in callback, it fails! – harsh Jan 08 '14 at 19:02
  • Could you provide more details on how it crashes? What is the call stack? –  Jan 08 '14 at 19:43
  • I just get `segmentation fault (core dumped)` error. Is there any way to view the call stack? I'm using Eclipse – harsh Jan 08 '14 at 19:48
  • You need to run this thing under debugger. I never debugged C++ under eclipse. Try "Debug As" rather than "Run As". –  Jan 08 '14 at 19:50
  • yes. I tried single stepping when the dc->print() is called in constructor the message prints fine but when dc->print() is called from the callback, it gives cannot access memory – harsh Jan 08 '14 at 20:07
  • I can't chat from work, and SO does not like long comment chains. You need to carefully use the debugger to look at all the data. In particular, compare `this` in the constructor with the parameter passed to callback. Compare dc at the end of the constructor with dc at in the callback. –  Jan 08 '14 at 20:22
  • Solved it by changing static void `callbk(void*)` to `static void callbk(Fl_widget*, void*)` – harsh Jan 08 '14 at 21:01
  • The giveaway line (which I missed) was `b->callback((Fl_Callback*)callbk, this);`. The cast tells us that something is wrong with the callback function. No cast should be necessary. –  Jan 10 '14 at 14:48