• Saves Valuable Time
  • Trusted Accuracy for 12 Years
  • 15-Day Money-Back Guarantee

C++ Equivalent to Java Anonymous Inner Classes

The closest equivalent to Java anonymous inner classes in C++ is to use a private class which implements the corresponding interface (but if the interface is a functional interface, then the closest equivalent is to replace the functional interface with a function pointer and the anonymous inner class with a lambda).

Java C++
public class TestClass
{
    private void TestMethod()
    {
        MyInterface localVar = new MyInterface()
        {
            public void method1()
            {
                someCode();
            }
            public void method2(int i, boolean b)
            {
                someCode();
            }
        };
    }
}
class TestClass
{
private:
    void TestMethod()
    {
        MyInterface *localVar = new MyInterfaceAnonymousInnerClass(this);
    }

private:
    class MyInterfaceAnonymousInnerClass : public MyInterface
    {
    private:
        TestClass *outerInstance;

    public:
        MyInterfaceAnonymousInnerClass(TestClass *outerInstance)
        {
            this->outerInstance = outerInstance;
        }

        virtual void method1()
        {
            someCode();
        }
        virtual void method2(int i, bool b)
        {
            someCode();
        }
    };
};


Use Java to C++ Converter to convert from Java to C++.     

Additional resource: Java and C++ Equivalents


Copyright © 1997 – 2017 Tangible Software Solutions Inc.