Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Class Initialization in C++

Tags:

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

like image 253
Rami Hashan Avatar asked Oct 30 '25 10:10

Rami Hashan


1 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

like image 190
Christian Hackl Avatar answered Nov 02 '25 02:11

Christian Hackl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!