3

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?

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
Mohammed Li
  • 823
  • 2
  • 7
  • 22

1 Answers1

1

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);