Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function pointers vs Subclasses

Tags:

c++

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

typedef void TimerCallback(void *args);
class Timer{
public:
  Timer();
  ~Timer();
  void schedule(TimerCallback *callback, void *args, long timeout)=0;
  void cancel();
};

Version 2

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 you have any other suggestions in this regard.

Please let me know if I am not clear in this regard.

Thanks

like image 475
user630286 Avatar asked Nov 29 '22 13:11

user630286


1 Answers

I would say std::function and std::bind. Then it doesn't matter if you want to use inherited classes, standalone functions, member functions or lambdas.


By the way, if anyone is curious I made a simple timer event handling some time ago, as an answer to another question. It's showcasing the use of e.g. std::function and std::bind: https://stackoverflow.com/a/11866539/440558.

like image 64
Some programmer dude Avatar answered Dec 15 '22 06:12

Some programmer dude