Abstract class initialization in C ++

In Java, you can initialize an abstract class without having to have a class that derives from it, simply by implementing an abstract method. Example:

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 this in C ++?

+3


source to share


3 answers


C ++ doesn't 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's 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 are so popular in programming these days that Java 8 supports them as well:

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

+2


source


Java does not allow instantiating abstract classes without invoking a non-abstract class from it. This allows you to infer the "inline" class directly at the time 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();
}

      

+2


source


The answer is simply no. The Java function you are talking about is called "Anonymous Classes" and this kind of function just doesn't exist in C ++.

+1


source







All Articles