I am in a position to choose between function pointers and subclassed objects. To make it clear, say I have to notify some object of some action (a timer for example); refer to the following two choices (a very basic code for demo purposes):
Version 1
1 2 3 4 5 6 7 8
typedefvoid TimerCallback(void *args);
class Timer{
public:
Timer();
~Timer();
void schedule(TimerCallback *callback, void *args, long timeout)=0;
void cancel();
};
Version 2:
1 2 3 4 5 6 7 8 9 10 11 12 13
class TimerTask{
public:
TimerTask();
virtual ~TimerTask();
void timedout()=0;
};
class Timer{
public:
Timer();
virtual ~Timer();
void schedule(TimerTask *callback, long timeout)=0;
void cancel();
};
which one is the standard C++ way and which one is efficient?
Please let me know if I am not clear in this regard.
Neither. The usual C++ way is to pass a function object (e.g. the result of a bind(), a lambda expression, or a user-defined class with an operator() to call back). They are generally more efficient than function pointers or your callback object with a virtual function call because they are much easier to inline.
In the case of a library that needs to be able to be compiled with one compiler and linked to code compiled in another, I don't think virtual inheritance or std::function are acceptable. Function pointers are more universal, unfortunately, but you can always restrict users of your library to compile the library with the same compiler and settings as the code they're linking to.