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.
You can easily inherit from that class:
However, you can't override HandleTimer in your subclass and expect this to work:
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:
This way, HandleTimer can still be used from C functions, just make sure to always pass the "real" object as the "void* Arg".
To some extent the traits pattern lets you inherit and redefine static methods.
First start with a base class:
Then derive it and redefine some methods:
And now call the methods via a traits class:
ideone demo
The traits class lets you reuse the static method
base::shout
while "overriding"base::talk
withderived::talk
. Still, there are several difference with actual inheritance:It works with static fields and typedefs too, the best example is std::iterator_traits.
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
.