How to Work with Events in a C++ Class

Environment: All ANSI C++ compilers

If you want to create a C++ class that calls clients' functions (events), you can do that in two ways. The first way is to call a global function through a function pointer that is a private member of your class. The client has to set that function pointer if it wants to handle that event. So, your class has two constructors, one with a function pointer and the other without it. If the client wants to handle an event, it has to create an instance of your class with the constructor that has a function pointer as the argument.

The second way is to call a class member function of the client class through the interface that is provided with your class package. The client has to inherit that interface and implement an event function if it wants to handle that event. So, your class has two constructors, one with an event interface pointer and the other without it. If the client wants to handle an event, it has to create an instance of your class with the constructor that has a function pointer as the argument; for example, "CEvent(this)". Here is the code for both ways:

Global way:

class ClassWithEvents
{
private:
  int i;
  void (*iChange)(int &);
public:
  ClassWithEvents();
  ClassWithEvents(void (*iChange)(int &));
  void set_i(int);
  int get_i(void);
};

ClassWithEvents::ClassWithEvents()
{
  this->iChange = 0L;
  this->i = 0;
}

ClassWithEvents::ClassWithEvents(void (*iChangeHandler)(int &))
{
  this->iChange = iChangeHandler;
  this->i = 0;
}

void ClassWithEvents::set_i(int iNum)
{
  this->i = iNum;

  if(this->iChange)
  {
    this->iChange(this->i);
  }
}

int ClassWithEvents::get_i(void)
{
  return this->i;
}

void myEvent(int &iNum)
{
  printf("Value of property 'i' = %d.\n", iNum);
}

void main(void)
{
  ClassWithEvents objClassWithEvents(myEvent);

  objClassWithEvents.set_i(4);
}


Class way:

class ClassWithEventsEvents
{
public:
  virtual void iChange(int &) = 0;
};

class ClassWithEvents
{
private:
  int i;
  ClassWithEventsEvents *objClassWithEventsEvents;

public:
  ClassWithEvents();
  ClassWithEvents(ClassWithEventsEvents *);
  void set_i(int);
  int get_i(void);
};


ClassWithEvents::ClassWithEvents()
{
  this->objClassWithEventsEvents = 0L;
  this->i = 0;
}

ClassWithEvents::ClassWithEvents(ClassWithEventsEvents
                                 *objClassWithEventsEventsHandler)
{
  this->objClassWithEventsEvents =
        objClassWithEventsEventsHandler;
  this->i = 0;
}

void ClassWithEvents::set_i(int iNum)
{
  this->i = iNum;

  if(objClassWithEventsEvents)
  {
    objClassWithEventsEvents->iChange(this->i);
  }
}

int ClassWithEvents::get_i(void)
{
  return this->i;
}


class EventHandler : public ClassWithEventsEvents
{
private:
  void iChange(int &iNum)
  {
    printf("Value of property 'i' is = %d.\n", iNum);
  }

public:
  ClassWithEvents *objClassWithEvents;

  EventHandler()
  {
    objClassWithEvents = new ClassWithEvents(this);
  }

  ~EventHandler()
  {
    delete objClassWithEvents;
  }

};

void main(void)
{
  EventHandler objEventHandler;

  objEventHandler.objClassWithEvents->set_i(4);
}

Downloads

Download source - 23 Kb


Comments

  • about event class in c++

    Posted by anurag kumar on 10/26/2012 04:09am

    i am beginner in c++ and i am working on snake game project.but i need some special command or class,whatever.i want to move an object on canvas without waiting for any key press.but when i will press any key to move in some other direction, then it should do,otherwise move forward

    Reply
  • >>Try using the notifier/observer pattern

    Posted by cathal.mchale on 11/12/2011 06:23pm

    From any design pattern book: The observer pattern is for one to many relationships (and in particular for when the event listeners are dynamic). If the relationship is singular and static then the observer pattern is an unnecessary overhead. It's fine in C# because you're given the plumbing for free (attach / detach handlers). Useful article. Thanks!

    Reply
  • Try using the Notifier/Observer pattern instead

    Posted by Legacy on 11/20/2002 12:00am

    Originally posted by: Guy Roshto

    The article does a fair of job of describing how to implement callbacks in C++ but has little to do with events. If your interested in handling events in C++ (not C#) then I suggest you take a look at the Notifer/Observer pattern. The "Design Patterns" book is a must read for all Object Oriented developers!

    -Guy

    Reply
  • No true events

    Posted by Legacy on 11/19/2002 12:00am

    Originally posted by: vipullal

    The article that is presented here is not like true C# events. Specifically, the pointer passed (iChange parameter in the constructor) can only be a pointer to a static function, not a member function of a class. C# allows member functions to be passed as event handlers. You can simulate this in C++, but requires some extra effort.

    Reply
  • This is ok but isn't it too easy for most of them?

    Posted by Legacy on 11/18/2002 12:00am

    Originally posted by: HSMin

    These simple call-back mechanism would be familiar to most programmers. Granted some of them would learn some from this article but...

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With 81% of employees using their phones at work, companies have stopped asking: "Is corporate data leaking from personal devices?" and started asking: "How do we effectively prevent corporate data from leaking from personal devices?" The answer has not been simple. ZixOne raises the bar on BYOD security by not allowing email data to reside on the device. In addition, Zix allows employees to maintain complete control of their personal device, therefore satisfying privacy demands of valued employees and the …

  • Available On-Demand Today's changing workforce dynamics, economic challenges, and technological advances are placing immense pressure on business leaders to turn their focus on people – their most valuable asset – in order to remain competitive. Research shows that a significant number of new employees quit within one year of taking a new job*. Whether it's through a merger and acquisition, or standard hiring process, like any first impression, early experiences shape their opinions of their new …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds