What does this line means:
bool operator() (const song& s);
I am not able to understand that line with operator. Is operator some kind of keyword in c++?
What does this line means:
bool operator() (const song& s);
I am not able to understand that line with operator. Is operator some kind of keyword in c++?
operator
is a keyword used to define how your class will interact with the normal operators. It include things like +, -, *, >> ect.
You can find a full list at cppreference.
The way it's written is the keyword operator
followed by the operator. So, operator+
, operator-
etc.
operator()
refers to the function operator. If it's defined, then we can call the object like a function.
MyClass foo;
foo(); //foo is callable like a function. We are actually calling operator()
In your example, operator()
is the function call operator and (const song& s)
is the parameter passed to the function.
Can we use () instead of {} for function scope?
No, we cannot. bool operator() (const song& s);
is a function declaration, not a definition. It declares a special function called operator()
. operator()
as a whole is the name of the function. The following (const song& s)
is the list of function arguments. A definition of that function could look like this:
#include <iostream>
struct song {
char const* name;
};
struct A {
void operator()(const song& s) {
std::cout << "Received a song: " << s.name << '\n';
}
};
int main() {
A a;
// Here's one way you call that function:
a(song{"Song1"});
// Here's another way
a.operator()(song{"Song2"});
}
This is called operator overloading. You can learn more about it here.