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 {
std::string name;
double freq;
};
class Journal {
public:
std::string title;
std::string message;
int idNum;
};
int main() {
Note a { "A", 440.0};
Journal journal {"hello, world", "just me, a class", 003};
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
- ,
: