Jeffrey Chen Jeffrey Chen - 1 month ago 9
Java Question

Implementing an interface in C++

How can I do this in C++

interface ActionListener { void actionPerformed(); }
jButton.addActionListener(
new ActionListener(){ void actionPerformed() { do something } }
);


So far I know this,

class ActionListener {
public :
virtual ~ActionListener(){}
virtual void actionPerformed() = 0;
}


After this what do I do ... any keywords to do this kind of implemention would also help.

Answer

C++ doesn't really have anonymous classes like you find in Java. The usual thing is just to declare a subclass that inherits from the interface class. The closest you come to Java's anonymous class instance is something like this:

class : public ActionListener {
public:
    virtual void actionPerformed() {
        // do something
    }
} listener;
thing.addActionListener( listener );
Comments