0

In C++ I have seen a functioning library with a function with this signature

DocumentReference::DocumentReference(model::ResourcePath path, std::shared_ptr<Firestore> firestore)
    : firestore_{std::move(firestore)} {
    // code here removed for https://stackoverflow.com/
}

But the library calls the function using {} instead of ().

return DocumentReference{
    ResourcePath::FromString(document_path),
    shared_from_this()
};

What difference does calling a function with {} instead of () make?

phuclv
  • 37,963
  • 15
  • 156
  • 475
heliam1
  • 133
  • 2
  • 9
  • 2
    https://en.cppreference.com/w/cpp/language/constructor - ref. “class-or-identifier brace-init-list” for the specific case in the shown code. There are various other forms where braces (`{}`) can also be used for initialization, which can be navigated to from that link. The braces are _never_ used to invoke a function/method. – user2864740 Sep 06 '20 at 03:43

2 Answers2

4

It's not "calling a function". DocumentReference::DocumentReference is a constructor. There are many ways to construct an object and {} is one of those. See

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Wait, a constructor isn't a function? Since when this has changed? – πάντα ῥεῖ Sep 06 '20 at 04:23
  • 2
    @πάνταῥεῖ Syntactically speaking, `type(expr)` is a cast which eventually calls the constructor for you, it isn't actually "calling the constructor". This is also why `type{expr}` make sense. – Passer By Sep 06 '20 at 04:35
  • Thanks for the help everyone, I wasn't able to find this out on my own as I was indeed misreading the constructor as a function and thus found no relevant results regarding () vs {} for C++ functions. I think we should leave the title of the question 'function' and not 'constructor', since {} can be used as function syntax in other languages e.g. Kotlin. – heliam1 Sep 06 '20 at 04:40
  • 2
    @heliam1 Technically a constructor _is a_ function like any other, but with special purpose and allowing syntax which isn't applicable with other _"normal"_ functions. – πάντα ῥεῖ Sep 06 '20 at 04:44
2

What difference does calling a function with {} instead of () make?

No differences in this case. Both of which just initialise the DocumentReference object.

It's preferable to use {} though.

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es23-prefer-the--initializer-syntax

artm
  • 17,291
  • 6
  • 38
  • 54