-1

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.

Asher Yartsev
  • 77
  • 3
  • 9

2 Answers2

4

It depends on whether the "(5)" is being used to construct an object or called on an already-existing object:

foo f(5); // calls the constructor
f(5);     // calls operator()
user1610015
  • 6,561
  • 2
  • 15
  • 18
0

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
Szabolcs Dombi
  • 5,493
  • 3
  • 39
  • 71