Abstract Class Initialization in C++

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++?

Answers


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


Java does not allow instantiating abstract classes without deriving a non-abstract class from it. It only allows you to derive the class “inline”, directly at the point of instantiation, which is known as anonymous classes.

You can achieve a similar effect in C++.

#include <iostream>

struct ABC
{
  virtual void f() = 0;
  virtual ~ABC() {}
};

int
main()
{
  struct : ABC { void f() override { std::cout << "okay\n"; } } anon {};
  anon.f();
}

The answer is simply no. the Java feature you are talking about called "Anonymous Classes" and this kind of feature simply does not exists in C++.


Need Your Help

How to drag a polygon?

java awt mouseevent polygon java-2d

I have drawn a polygon in Java using java.awt.Polygon. I want to move the polygon with mouse (I want to drag it). I know that I have to use mouseDragged method in addMouseMotionListener. That wa...