Asher Yartsev Asher Yartsev - 3 months ago 15
C++ Question

operator() overload and c'tor ambiguity in function objects

assuming we have the next function object:

class foo{
private:
int counter;
public:

foo(int counter): counter(counter){}
foo& operator=(const foo& ){...}
bool operator() (int variable){....}

}

int main(){
foo f(4);
foo x(5);
x = f(4);
return 0;
}


how does the compiler knows how to respond to:
x = f(5)
?
I've been searching for a while on the web and in Stack and haven't found exact answer, if its a repost , tell me and i'll delete the question.

Answer

I added a simple method called eval to explain it:

class foo {
private:
    int counter;

public:

    foo(int counter): counter(counter) {}

    bool operator() (int variable) {
        return variable < counter;
    }

    bool eval(int variable) {
        return variable < counter;
    }
};
  • foo is a class not a method.
  • an instance of foo can be used like a method.
  • calling foo(5) will create an instance of foo where the counter = 5.

  • eval is a member function of foo. (for now this will do the same as the () operator)

You can call eval like this:

foo f = foo(5); // create an instance of `foo`
f.eval(3); // returns true    ->   3 < 5
f.eval(0); // returns false   ->   6 < 5

You can also use the () operator:

foo f = foo(5); // create an instance of `foo`
f(3); // returns true    ->   3 < 5
f(0); // returns false   ->   6 < 5

NOTE:

You can also write (but don't do it):

foo f = foo(5); // create an instance of `foo`
f.operator()(3); // returns true    ->   3 < 5
f.operator()(0); // returns false   ->   6 < 5
Comments