Objects that are instances of classes that have an overloaded operator(), the function call operator, are considered to be function objects.
We can use them as i f they were functions, so it looks like we call an object. Sometimes they are called functors.
class Location {
private:
int longitude, latitude;
public:
Location(){};
Location(int lg, int lt) { longitude = lg; latitude = lt; }
void show() const { cout<< longitude << “ “ << latitude<<endl; }
Location operator+(Loc op2);
Location operator()(int lg, int lt);
};
Location Location::operator+ (Loc op2)
{
Location tmp;
tmp.longitude = op2.longitude+longitude;
tmp.latitude = op2.latitude+latitude;
return tmp;
}
Location Location::operator()(int lg, int lt)
{
longitude = lg;
latitude = lt;
return *this;
}
int main()
{
Location ob1(10,20), ob2(1,1);
ob1.show();
ob1(7,8);
ob1.show();
ob1 = ob2 + ob1(10,10);
ob1.show();
return 0;
}
Output:
10 20
7 8
11 11
It looks like we are calling a function! When you are reading code you need to be careful not to confuse them with constructors!
Loc ob1(10, 20); // Constructor
ob1(7, 8); // Function object
The function object call is translated by the compiler into
ob1.operator()(7, 8