Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call class as function in c++ [duplicate]

Tags:

c++

class

in python you can define a class A

class A(object):
    .....

    def __call__(self, bar):
        #do stuff with bar
        ....

which allows me to use it like this:

bar = "something"
foo = A()
foo(bar)

I would like to do the same thing in c++, but I did not find anything, Is this possible or did I overlook something?

like image 750
Mohammed Li Avatar asked Aug 03 '26 05:08

Mohammed Li


1 Answers

The name of the class is reserved in C++ for constructors. You can create a constructor with parameters of the type you need, but it will always be creating a new instance of the class. If you need to perform some task that is not instantiating the class, create a method using a different name.

class A {
    ...
public:
    A(); // Constructor with no parameters
    A(BarType bar); // Constructor with parameter BarType
    void someMethod(BarType bar); // Method that takes bar and performs some operation
}

Usage:

BarType bar = BarType();
A aInstance = A(bar);

To perform some task without instantiating with parameters:

A aInstance = A();
BarType bar = BarType();
aInstance.someMethod(bar);
like image 166
O. Weissberg Avatar answered Aug 05 '26 19:08

O. Weissberg



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!