Amarjeet Sharma
Amarjeet Sharma

Reputation: 188

Calling convention of overloaded operator within structure?

I was revisiting the concepts of structures in C++ before the lectures and written the following:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct isOdd{
  bool operator()(int x){
    return x%2;
  }
};

int main(){
 vector<int> v {3,4,2,1,65,2,4,65,2,9,8,5,7};

 int count = count_if(begin(v), end(v), isOdd());

 cout << "size of vector: " <<v.size() << endl;
 cout << "count of odds: " <<count << endl;
 return 0;
}

Then I realize that in calling function of structure isOdd, I have used the syntax: isOdd() but I have only overridden the () operator. So how the calling convention isOdd() is working because the calling a function of structure is like: structure::function-name(); or structure-object.functions-name();

Can somebody elaborate the doubt?

Thanks.

Upvotes: 1

Views: 122

Answers (1)

WhiZTiM
WhiZTiM

Reputation: 21576

Then I realize that in calling function of structure isOdd, I have used the syntax: isOdd() but I have only overridden the () operator.

No, You called the implicit compiler generated default constructor, thereby creating a temporary object of isOdd.

For example: If you wanted to test it on a single number without creating a named isOdd object, you could:

bool is_odd = isOdd()(4);
                 //^^ Creates a temporary object

Optimizing Compilers will elide the creation of the temporary object since it neither has observable side effects nor a state.

Upvotes: 1

Related Questions