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
}
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.
No, there's no equivalent in C++, nor could there be for the way classes are commonly used in C++.
In Java, this creates a new class type which derives from MyClass and overrides myMethod(). This works, because variables of type MyClass are just references, so those variables can hold references to derived classes.
In C++, variables of type MyClass are not references. They must be of type MyClass, nothing else. While it is possible for MyClass & to hold a reference to a class that derives from MyClass, the use of references (or pointers) in this case is very unidiomatic C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With