1

One of the nice things in Java is implementing interface. For example consider the following snippet:

interface SimpleInterface()
{
public: void doThis();
}

...
SimpleInterface simple = new SimpleInterface()
{
@Override public doThis(){ /**Do something here*/}
}

The only way I could see this being done is through Lambda in C++ or passing an instance of function<> to a class. But I am actually checking if this is possible somehow? I have classes which implements a particular interface and these interfaces just contain 1-2 methods. I can't write a new file for it or add a method to a class which accepts a function<> or lambda so that it can determine on what to do. Is this strictly C++ limitation? Will it ever be supported?

Somehow, I wanted to write something like this:

thisClass.setAction(int i , new SimpleInterface()
{
protected:
virtual void doThis(){}
});

One thing though is that I haven't check the latest spec for C++14 and I wanted to know if this is possible somehow.

Thank you!

5
  • 4
    That's called an anonymous inner class. You should use lambdas. Commented Feb 19, 2015 at 16:19
  • That's my problem, they just had a couple of methods. Gonna create separate .h/ h. with .cpp files for them which will only be used once. Though this is possible by having a member variable function<> on a class, still its just function. How about the entire class/interface implementation? Commented Feb 19, 2015 at 16:21
  • @SLaks, thats good to know, can you show some examples? Commented Feb 19, 2015 at 16:23
  • @NeonWarge: Examples of what? Commented Feb 19, 2015 at 16:26
  • MAYBE (because I'm not good at or sure if it will work), you can do this with macro's.. Commented Feb 19, 2015 at 17:56

4 Answers 4

6

Will it ever be supported?

You mean, will the language designers ever add a dirty hack where the only reason it ever existed in one language was because those designers were too stupid to add the feature they actually needed?

Not in this specific instance.

You can create a derived class that derives from it and then uses a lambda, and then use that at your various call sites. But you'd still need to create one converter for each interface.

struct FunctionalInterfaceImpl : SimpleInterface {
    FunctionalInterfaceImpl(std::function<void()> f)
        : func(f) {}
    std::function<void()> func;
    void doThis() { func(); }
};
Sign up to request clarification or add additional context in comments.

Comments

2

You seem to think each class needs a separate .h and .cpp file. C++ allows you to define a class at any scope, including local to a function:

void foo() {
  struct SimpleInterfaceImpl : SimpleInterface
  {
  protected:
    void doThis() override {}
  };

  thisClass.setAction(int i , new SimpleInterfaceImpl());
}

Of course, you have a naked new in there which is probably a bad idea. In real code, you'd want to allocate the instance locally, or use a smart pointer.

3 Comments

It is very hard for me to communiate this because i don't really know what its called. Yeah I think I did somehow, so far we can't do like: thisClass.setAction(int i, new SimpleInterface(){});? This is the one I have right now and it litters my header/implementation file. I just asked because I am doing a clean up and I could find anything useful from the web but I am still hopeful on the new standard.
@NeonWarge I know exactly what you mean. C++ does not allow you to do it as fully inline (within an expression) as Java does. But it does allow you to do it at function scope, as I've shown. How can that litter header files?
if you have ` thisClass.setAction(int i, new SimpleInterface(){ });` littering your code, you need to define it in one place, and use that definition everywhere else.
1

This is indeed a "limitation" of C++ (and C#, as I was doing some research some time ago). Anonymous java classes are one of its unique features.

The closest way you can emulate this is with function objects and/or local types. C++11 and later offers lambdas which are semantic sugar of those two things, for this reason, and saves us a lot of writing. Thank goodness for that, before c++11 one had to define a type for every little thing.

Please note that for interfaces that are made up of a single method, then function objects/lambdas/delegates(C#) are actually a cleaner approach. Java uses interfaces for this case as a "limitation" of its own. It would be considered a Java-ism to use single-method interfaces as callbacks in C++.

Local types are actually a pretty good approximation, the only drawback being that you are forced to name the types (see edit) (a tiresome obligation, which one takes over when using static languages of the C family).

You don't need to allocate an object with new to use it polymorphically. It can be a stack object, which you pass by reference (or pointer, for extra anachronism). For instance:

struct This {};

struct That {};

class Handler {
  public:
    virtual ~Handler ();
    virtual void handle (This) = 0;
    virtual void handle (That) = 0;
};

class Dispatcher {
    Handler&    handler;
  public:
    Dispatcher (Handler& handler): handler(handler) { }

    template <typename T>
    void dispatch (T&& obj) { handler.handle(std::forward<T>(obj)); }
};

void f ()
{
    struct: public Handler {
        void handle (This) override { }
        void handle (That) override { }
    } handler;
    Dispatcher dispatcher { handler };
    dispatcher.dispatch(This {});
    dispatcher.dispatch(That {});
}

Also note the override specifier offered by c++11, which has more or less the same purpose as the @Override annotation (generate a compile error in case this member function (method) does not actually override anything).

I have never heard about this feature being supported or even discussed, and I personally don't see it even being considered as a feature in C++ community.

EDIT right after finishing this post, I realised that there is no need to name local types (naturally), so the example becomes even more java-friendly. The only difference being that you cannot define a new type within an expression. I have updated the example accordingly.

Comments

-1

In c++ interfaces are classes which has pure virtual functions in them, etc

class Foo{
   virtual Function() = 0;
};

Every single class that inherits this class must implement this function.

1 Comment

The OP did not ask for a C++ equivalent of interfaces. He wanted to know if C++ supports something like anonymous classes (which also work with abstract classes and not only with interfaces, btw).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.