views:

1702

answers:

2
struct TimerEvent
{
   event Event;
   timeval TimeOut;
   static void HandleTimer(int Fd, short Event, void *Arg);
};

HandleTimer needs to be static since I'm passing it to C library (libevent).

I want to inherit from this class. How can this be done?

Thanks.

+8  A: 

You can easily inherit from that class:

class Derived: public TimerEvent {
    ...
};

However, you can't override HandleTimer in your subclass and expect this to work:

TimerEvent *e = new Derived();
e->HandleTimer();

This is because static methods don't have an entry in the vtable, and can't thus be virtual. You can however use the "void* Arg" to pass a pointer to your instance... something like:

struct TimerEvent {
    virtual void handle(int fd, short event) = 0;

    static void HandleTimer(int fd, short event, void *arg) {
        ((TimerEvent *) arg)->handle(fd, event);
    }
};

class Derived: public TimerEvent {
    virtual void handle(int fd, short event) {
        // whatever
    }
};

This way, HandleTimer can still be used from C functions, just make sure to always pass the "real" object as the "void* Arg".

João da Silva
A: 

You've got a bit of a conflict here in your question. When you pass &TimerEvent::TimerHandler to a C library, you do exactly that. You could also have passed &DerivedTimerEvent::TimerHandler, if you wanted. But you can't pass &TimerEvent::TimerHandler and expect the C library (!) to figure out you actually meant &DerivedTimerEvent::TimerHandler.

MSalters