1

I have a question about virtual functions in C++. I have spent the last hour searching but I'm getting nowhere quickly and I was hoping that you could help.
I have a class that handles transmitting and receiving data. I would like the class to be as modular as possible and as such I would like to make an abstract/virtual method to handle the received messages.
Although I know I could create a new class and overwrite the virtual method, I don't really want to have to create a large array of new classes all implementing the method different ways. In Java you can use listeners and/or override abstract methods in the body of the code when declaring the object as can be seen in the example.

JTextField comp = new JTextField();   
comp.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //Handler Code
    }
});

Is this possible in C++ or is there a better approach to this sort of problem?

Cheers and Many thanks in advance,
Chris.

Goibniu
  • 2,212
  • 3
  • 34
  • 38
Chris192
  • 43
  • 5

3 Answers3

3

Have look at this other SO post Does C++0x Support Anonymous Inner Classes as the question sounds similar.

Functors (function objects) or lambdas could be suitable alternatives.

Community
  • 1
  • 1
Drew MacInnis
  • 8,267
  • 1
  • 22
  • 18
1

In C++, you need to declare a new class:

class MyActionListener: public ActionListener
{
    public:
       void actionPerformed(ActionEvent evt) { ... code goes here ... }
}; 
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

The question has already been answered but I thought I'd throw this in for good measure. The SO discussion linked in the example is good but concentrates mostly on replicating the Java experience. Here's a more idiomatic C++ way of doing it:

struct EventArgs
{
    int param1;
    int param2;
};

class network_io
{
    typedef std::function<void (EventArgs)> Event;
    typedef std::vector<Event> EventList;

    EventList Events;

public:
    void AddEventHandler(Event evt)
    {
        Events.push_back(evt);
    }

    void Process()
    {
        int i,j;
        i = j = 1;
        std::for_each(std::begin(Events), std::end(Events), [&](Event& e)
        {
            EventArgs args;
            args.param1 = ++i;
            args.param2 = j++;

            e(args);
        });
    }
};

int main() 
{
    network_io ni;

    ni.AddEventHandler([](EventArgs& e)
    {
        std::cout << "Param1: " << e.param1 << " Param2: " << e.param2 << "\n";
    });

    ni.AddEventHandler([](EventArgs& e)
    {
        std::cout << "The Param1: " << e.param1 << " The Param2: " << e.param2 << "\n";
    });

    ni.Process();
}
Peter R
  • 2,865
  • 18
  • 19