Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compiler handle overloaded function call operators in functors?

Say I define, instantiate, and use an adder functor like so:

class SomeAdder {
    public:
        SomeAdder(int init_x): x(init_x) {}
        void operator()(int num) { cout << x + num <<endl; }
    private:
        int x;
};

SomeAdder a = SomeAdder (3);
a(5); //Prints 8

SomeAdder b(5);
b(5); //Prints 10

The constructor and the overloaded () operator are both called using double parenthesis and have the same types of parameters. How would the compiler determine which function to use during the instantiations of SomeAdder and the "function calls", as to implement the correct behavior? The answer seems like it would be obvious on the surface, but I just can't wrap my head around this thought.

Thanks for your time!

like image 954
Kelvin Lu Avatar asked Mar 03 '13 03:03

Kelvin Lu


People also ask

How does compiler handle function overloading?

The compiler selects which overloaded function to invoke based on the best match among the function declarations in the current scope to the arguments supplied in the function call. If a suitable function is found, that function is called. "Suitable" in this context means either: An exact match was found.

Which operators are overloaded for functors?

Which of the following operators are overloaded for functors? Explanation: () operator is overloaded to use functor property in a C++ program because this is the only operator used for a function call.

When you call an overloaded operator how compiler identified?

When you call an overloaded function or operator, the compiler determines the most appropriate definition to use, by comparing the argument types you have used to call the function or operator with the parameter types specified in the definitions.

What will happen when the function call operator is overloaded *?

The function call operator, when overloaded, does not modify how functions are called. Rather, it modifies how the operator is to be interpreted when applied to objects of a given type.


2 Answers

Every time an instance of a class is created the constructor method is called. Compiler for sure can determine constructor by its name. So it will be called first and operator () will be second.

like image 38
Pavel Malinnikov Avatar answered Sep 30 '22 14:09

Pavel Malinnikov


Your example compares constructor and member function which overloads operator(). The compiler knows which one to call and when. It is pretty much simple:

  • When an object is to be constructed, the constructor is called.

  • The member function is invoked on an already constructed object. In your case, the member function is operator().

That means, they're invoked in entirely different contexts. There is no ambiguity, no confusion.

like image 124
Nawaz Avatar answered Sep 30 '22 14:09

Nawaz