Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing default values in a struct

Tags:

c++

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?

like image 891
Joe Wilcoxson Avatar asked May 28 '13 00:05

Joe Wilcoxson


People also ask

Can you set default values in a struct?

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.

Can you initialize in struct?

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.

Are structs default initialized?

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.

Can you initialize variables in a struct C?

Structure members cannot be initialized with declaration.


1 Answers

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.

like image 143
Erik van Velzen Avatar answered Sep 22 '22 15:09

Erik van Velzen