Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ in function definition of abstract classes

I would like to know if it is possible to do Java style implementation of listener / abstract classes within a function.

In Java if I have an interface as follows:

public interface ExampleListener {
    public void callExampleListenerMethod();
}

I know can implement this interface within a method for some quick usage something like this:

someRandomJavaFunction{
   //do some stuff
   ExampleListener object = new ExampleListener() {
        @Override
        public void callExampleListenerMethod() {
            //do other stuff
        }
   });
}

Now is it possible to do the second Part somehow in C++ if I have an abstract class defined like this

class ExampleListener {

  public:
     virtual ~ExampleListener(); //virtual destructor is apparently important

     virtual void callExampleListenerMethod() = 0; //method to implement

};

Of course I can just simply use this as a Base class and I'm forced to implement the method. But is it possible to do a similar "on the fly" implementation to java?

like image 515
Arne Fischer Avatar asked May 09 '14 14:05

Arne Fischer


1 Answers

No, there is no equivalent of "on-the-fly" method implementation in C++. The closest thing you could do in C++ is a local class

void f()
{ 
    class MyLocalClass: public Listener
    {
        virtual void MyMethodOverride()
        {
             //... 
        }
    }

    Listener* pListener = new MyLocalClass;
    //...
}
like image 139
Armen Tsirunyan Avatar answered Sep 27 '22 23:09

Armen Tsirunyan