In Java you can initialize an abstract class without the need of having a class that derives from it by just implementing the abstract method. Ex:
public abstract class A { public abstract void a(); }
public class Test {
public static void main(String[] args) {
A b = new A() { @Override public void a() { System.out.println("Test"); } }
}
}
My question is: can you do something like that in C++?
C++ does not support this.
But C++ uses less OOP in general (with "OOP" in the sense of "using virtual functions"). In particular, since C++11, lambdas provide a powerful alternative to many OOP-based patterns in Java.
Here is a very simple example:
#include <functional>
#include <iostream>
void f(std::function<void()> a)
{
a();
}
int main()
{
f([]() { std::cout << "Test\n"; });
}
Or:
#include <iostream>
template <class Operation>
void f(Operation operation)
{
operation();
}
int main()
{
f([]() { std::cout << "Test\n"; });
}
In fact, lambdas have become so popular in programming these days that Java 8 supports them too:
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
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