1

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,180
  • 3
  • 27
  • 46
Mohammed Li
  • 740
  • 2
  • 6
  • 18
  • 2
    I do not understand your example. What is the purpose of assigning `foo`? You don't do anything with it. Please explain what you are trying to accomplish *in words*. For example, "construct an `A` from a string." – Cody Gray Feb 25 '16 at 12:50
  • 7
    Learn about *operator overloading in C++*. Overloading `operator()` might be of most interest to you. – Some programmer dude Feb 25 '16 at 12:51
  • 3
    You want a [function object](https://en.wikipedia.org/wiki/Function_object#In_C_and_C.2B.2B) – Revolver_Ocelot Feb 25 '16 at 12:51

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