Function was put into a curly bracket in order to initialize the member in class. What is its syntax?

144 views Asked by At

The code is shown here:

class Basket{
public:
/*other contents*/
private:
    // function to compare shared_ptrs needed by the multiset member
    static bool compare(const std::shared_ptr<Quote> &lhs,
        const std::shared_ptr<Quote> &rhs)
    { return lhs->isbn() < rhs->isbn(); }
    // multiset to hold multiple quotes, ordered by the compare member
    std::multiset<std::shared_ptr<Quote>, decltype(compare)*>
        items{compare};
};

We initialize our multiset through an in-class initializer. Commonly we put a same class object in the curly bracket. Why a function can be put here? I can't understand;

It's explained in the book C++ primer like it: The multiset will use a function with the same type as our compare member to order the elements. The multiset member is named items, and we’re initializing items to use our compare function.

I can understand the logic, but what is the syntax used here?

2

There are 2 answers

6
nick On BEST ANSWER

items{compare}; is a call to one of the overloads of the constructor of std::mulitset.

Which one of the overloads to use is decided by the compiler from looking at your argument type: compare matches the description of a "comparison function object" (see link), so the second invocation is used.

It is a pointer to a function, taking two values as parameters and returning a boolean is the main point here. That function can then be later called by the multiset object to sort its members. Look up "callback functions" if you want to learn more about this concept. See here for a start: Callback functions in C++

What you're refering to with

Commonly we put a same class object in the curly bracket.

would be using the copy-constructor (no. 6 in the link). Just another way to create the same type of object.

There are questions here on SO about using a constructor with {} vs () if that is part of the confusion: What's the difference between parentheses and braces in c++ when constructing objects

0
user12002570 On

Commonly we put a same class object in the curly bracket. Why a function can be put here?

What actually happens is that compare when used inside the braces {} decays to a pointer to function due to type decay(as it is a static member function). Then this decayed function pointer is passed as argument to one of the std::multiset's constructor which will make std::multiset to use this compare function as comparator.

//--------------------------------vvvv-------------------->we're passing a pointer to static member function as argument for this first parameter
explicit multiset( const Compare& comp, const Allocator& alloc = Allocator() );