0

I know the X{} is the default initializer from internet, and I still don't know what the X() means what. is it initializer? but why the int value(); is not ok?

so I want to know what difference is between X() and X{}. thank you!

class X{
public:
    void operator()(string str)
    {
        cout << "calling functor x with parameter" << str << endl;
    }
    
};

int main()
{
    X foo;
    // foo("hi");
    X()("hi");      // I don't know what happen when I see the code
    X c = X{};      // this is the default initializer 
    X a = X();      // but what it is
    int value{};
    // int value(); // this is error
}
Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38
milaimac
  • 11
  • 1
  • 2
    `int value();` is a declaration of a function that takes no arguments and returns an `int`. Braced initialization was introduced to distinguish this situation and ones like it that arise with more complicated combinations of types. – Nathan Pierson Oct 22 '21 at 01:42
  • Related: [https://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization](https://stackoverflow.com/questions/24953658/what-are-the-differences-between-c-like-constructor-and-uniform-initialization) – drescherjm Oct 22 '21 at 01:44
  • You are asking a complicated question. There do exist different kinds of initialization in c++. I suggest you reading this: https://en.cppreference.com/w/cpp/language/list_initialization and the `see also` part. – Yves Oct 22 '21 at 01:58
  • [cppreference.com - Initialization](https://en.cppreference.com/w/cpp/language/initialization) – David C. Rankin Oct 22 '21 at 01:59
  • `X()` and `X{}` are all Value initialization because they have no any parameter. `X(param1, param2)` is List initialization and `X(param1, param2)` is Direct initialization. Well, it's complicated but you needn't make them all very clear. You can simply make the `X{}` as your prior choice. – Yves Oct 22 '21 at 02:03
  • With regards to why `int value();` is not OK: [Default constructor with empty brackets](https://stackoverflow.com/questions/180172/) – JaMiT Oct 22 '21 at 02:27
  • A lot is going on a here. Key words are `uniform initialization`, `most vexing parse`, and `call operator`. – Aykhan Hagverdili Oct 22 '21 at 02:35

0 Answers0