1

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++?

Evg
  • 25,259
  • 5
  • 41
  • 83
RajGM
  • 37
  • 6
  • need more context. – BobRun Dec 07 '19 at 06:02
  • Yes, `operator` is a keyword in C++. It allows one to overload operators---in this case the "call" operator. – jkb Dec 07 '19 at 06:04
  • 1
    Please don't tag languages unrelated to the question (Fixed) – ikegami Dec 07 '19 at 06:07
  • Yes, `operator` is a reserved keyword in C++. The scope of the "line" is presumably within a `class` or `struct` definition, and is a declaration of a member function named `operator()` that accepts a parameter of type `const song &` and return a `bool`. Given an instance of that `class` or `struct` named `x`, the expression `some_bool = x(some_song)` will call that function. The function does need to be defined though. In C, this question is off-topic. – Peter Dec 07 '19 at 06:07
  • check this https://stackoverflow.com/questions/317450/why-override-operator to understand use cases – hazirovich Dec 07 '19 at 06:07

2 Answers2

1

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.

super
  • 12,335
  • 2
  • 19
  • 29
1

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93