Search code examples
c++operator-overloadingpriority-queue

Why I should overload the () operator for priority_queue in a struct instead of a class?


I am wondering why the following overloading is wrong.

class comparator{
    bool operator()(string& s1, string& s2) {
        return s1[0] < s2[0];
    }
};

int main()
{
    priority_queue<string, vector<string>, comparator> myqueue;
    myqueue.push("a");
    myqueue.push("bb");
    myqueue.push("ccc");
    return 0;
}

It gives the error that

operator() cannot access private member declared in class comparator.

When I use "struct" instead of "class", it works.


Solution

  • I am wondering why the following overloading is wrong.

    Because the default access specifier of a class defined with the class keyword is private. You didn't specify the access specifier of the member function, so the default is used.

    The error message explains to you that the private member cannot be accessed. Private functions may only be named within the scope of the class. Since the template that you use is not defined within the scope of the class, it cannot use the private member function.

    The default access specifier of a class defined with the struct keyword is public. Public functions can be named from outside the class definition, so it works here.

    Why I should overload the () operator for priority_queue in a struct instead of a class?

    You can use class as well. But then you must specify the access specifier explicitly.

    P.S. The default access specifier is the one and only difference between classes defined with the keyword class, and classes defined with the keyword struct (which also called structs).