Search code examples
c++virtualdeclaration

Implement interface just in place in c++


I want to achieve such an outcome using c++:

Java:

public interface ITemp {
    void onCall(double value);
}

In main:

double d=2;
ITemp mVariable = new ITemp() {
@Override
    public void onCall(double value) {
    ... what to do... you can use 'd' variable...
    }
};

In C++:

class ITemp {
public:
    virtual void onCall(double something) =0;
    virtual ~ITemp();
};

In main:

double d=2;
ITemp mVariable = .... // I cannot instantiate class containing pure virtual method
// But I want to use variable d to create a method

Solution

  • You can't do exactly that since you can't create anonymous classes in C++, but you can do something similar:

    int main()
    {
        double d = 2;
        class T : public ITemp
        {
            double& m_v;
        public:
            T(double& v) : m_v(v) {}
            void onCall(double value)
            {
                // Do something with m_v;
                m_v *= value;
            }
        } t(d);
        t.onCall(4);
        std::cout << "d: " << d << std::endl;  // d is 8.
    }
    

    The reference ('&') makes m_v the same variable as d, but under a different name.