Oskuro Oskuro - 3 months ago 10
C++ Question

C++ Can virtual methods be implemented when declaring an object?

I'm back to working with C++ after quite a long while using Java almost exclusively, so I'm hitting snags when trying to do things I could do in Java but can't in C++.

In this case, in Java I could do something like this:

class MyClass
{
public void myMethod();
}

// -------

MyClass myObject = new MyClass(){
myMethod()
{
// Do stuff
}
};


In essence, I'm implementing the logic for myMethod() when declaring the MyClass object (Note that my syntax might be off).

I'm trying to find out if there's an equivalent for C++

My specific use case is a set of tests for a Server/Client architecture where the Test objects extend the base Server/Client abstract classes and implement the virtual methods controlling their behaviour.
I need to modify this behaviour for each specific test, and it would come in handy to be able to "inline" these implementations when declaring the Test objects, rather than having to implement several variations on the Test object for each specific test.

Thanks!

EDIT: I've implemented Smeeheey's answer as follows, and works like a charm

int main(...)
{

class TestServer : public BaseServer
{
public:
TestServer(...) : BaseServer(...){...} //Constructor

void virtualFunction(...){...} // Extended function
};

TestServer testInstance(...);

// Execute tests using testInstance object


}

Answer

You can actually come pretty close, with an anonymous local struct/class:

class MyClass
{
public:
    virtual void doStuff() = 0;
};

void doStuffWithMyStruct(MyClass& s)
{
    s.doStuff();
}

int main()
{
    class: public MyClass
    {
    public:
        void doStuff() override
        {
            std::cout << "Hello" << std::endl;
        }
    } s;

    doStuffWithMyStruct(s);

    return 0;
}

Note that in the above, the variable s has an anonymous type, very similar to Java. Its functions can be accessed in a reference to its base type. Live demo here.

Comments