CompEng88
CompEng88

Reputation: 1532

In function implementation of interface

In Java, if I have an interface, I can do something like this:

blah.setOnClickListner(new OnClickListner() {
     public void clicked() { // do something }
}

Can I do something similar in C++?

Upvotes: 2

Views: 66

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283614

C++ supports local classes. The syntax is the same as for any class type, except that member functions and static member variables must be defined inside the class body, not declared and defined later (there's no way to name the member from outside the enclosing function).

Beginning in C++11, they can be used as template type parameters, which makes them much much more useful.

It would look something like:

void Parent::func( EventProducer* blah )
{
    struct LocalListener : OnClickListener
    {
        virtual void clicked() { ... }
    };
    struct FancyLocalListener : OnClickListener
    {
        Parent* p;
        FancyLocalListener(Parent* p) : p(p) {} // but use better variable names, please ;)
        virtual void clicked() { p->func2(); }
    };

    blah->addOnClickListener(new LocalListener());
    blah->addOnClickListener(new FancyLocalListener(this));
}

(but watch out for leaks)

C++ tends not to use interfaces for this, though. A better design is to accept a functor for the listener, which in C++11 allows the use of lambdas (the compiler creates the local class for you).

Upvotes: 5

Related Questions