If I needed to initialize only a few select values of a C++ struct, would this be correct:
struct foo { foo() : a(true), b(true) {} bool a; bool b; bool c; } bar;
Am I correct to assume I would end up with one struct
item called bar
with elements bar.a = true
, bar.b = true
and an undefined bar.c
?
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.
You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. This process is called non-static member initialization, and the initialization value is called a default member initializer.
Structure members cannot be initialized with declaration.
You don't even need to define a constructor
struct foo { bool a = true; bool b = true; bool c; } bar;
To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With