Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct with boolean field default initialization?

Tags:

c++

I have the following use case, a struct with some boolean and int variables

struct a {

    int field1;
    bool field2;
    bool field3;

};

I am refactoring this code, and writing a constructor for the struct , the problem is the default initialization of fields.

I am not criticizing any language construct here, but ideally I would want null to be part of the language itself

i mean I should be able to define for struct a as

a : field1(null.int), field2(null.bool), field3(null.bool) {}

C++ does not allow it since null.int or null.bool are not defined. Is the only way to do in C++ is

a: field1(-1), field2(false), field3(false) {}
like image 274
kal Avatar asked Dec 11 '25 02:12

kal


2 Answers

You can do

struct a {
    a():field1(), field2(), field3() { }
    int field1;
    bool field2;
    bool field3;
};

And all fields will be zero and false respectively. If you want to say that the fields have an indeterminate value, i'm afraid you have to use other techniques. One is to use boost::optional:

struct a {
    a():field1(int()), field2(bool()) { }
    optional<int> field1;
    optional<bool> field2;
    optional<bool> field3;
};

Leaves field3 indeterminate. Access the values with *field_name. Test for a none value with field == boost::none or if(field) { ... }.

like image 68
Johannes Schaub - litb Avatar answered Dec 13 '25 14:12

Johannes Schaub - litb


If you're looking for a type with values {true, false, null}, that type is not bool. However, boost::optional<bool> is such a type. In the same way, boost::optional<int> can hold any int, or no int at all.

[edit] Or std::optional, since C++17.

like image 29
MSalters Avatar answered Dec 13 '25 15:12

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!