C ++, what is this underused constructor syntax?

EDIT: I don't think this is a duplicate of this other question , because another question just carries ()for {}in the constructors. While I note different behavior when the constructor is defined in struct, but not in class. (And, as stated in the comments, it's about using constructors that don't write them.) But I used to be wrong.

I came across this strange (for me) syntax for the constructor when learning:

Foo obj {i, j};
At first I thought that this would not work, and I told the student to rewrite it - however they were adamant, and he informed me that they pulled an example from cplusplus.com, which I could not find the link , so I tried anyway ... And it worked. Therefore, I experimented with it.

I also worked a little myself, and did not find a link to this constructor syntax on cplusplus.com. (Maybe he has a specific name?)

Here is what I did to experiment with it.

struct Note { //A musical note.
    std::string name;
    double freq;
    //Note(std::string s, double f): name(s), freq(f){}
    //Uncomment the constructor in order to use normal constructor syntax.
};

class Journal {
public:
    std::string title;
    std::string message;
    int idNum;
};

int main() {
    Note a { "A", 440.0}; //Works with or without a constructor.
    //Note a("A",440.0); //Works ***only*** with a defined constructor.

    //Journal journal("hello, world", "just me, a class", 002); //Works regardless of constructor definition.
    Journal journal {"hello, world", "just me, a class", 003}; //Works regardless of constructor definition.

    std::cout << a.name << " " << a.freq << std::endl;
    std::cout << journal.title << " " << journal.message << " " << journal.idNum << std::endl;

    return 0;

}

I found that it works with structures and classes regardless of whether they have a specific constructor.

Obviously, the default constructors work, but it confused me for several reasons:

  • I have never seen this syntax before (no wonder C ++ is huge)
  • He works
  • ,

:

  • , , , ( )?
+4
2

++ 11, , ,

int x (0);  // Constructor initialization
int x {0};  // Uniform initialization

:

  • () ( , )
  • {}

.

, ,

std::vector<int> v (100); // 100 elements
std::vector<int> v {100}; // one element of value 100

, , .

, ( ).

+3

" ". 8.5.4 ++ 14.

, , C, , .

+2

Source: https://habr.com/ru/post/1659217/


All Articles