user10607
user10607

Reputation: 3071

Default initialize a class with many boolean values?

Note: I can not use c++11.

I have a class with many boolean values and a string. It is expected to be used on the stack. Right now I use this:

class Lorem: public Ipsulum {
public:
Lorem() :
    has_foo(0),
    is_bar(0),
    is_on(0),
    is_a_pony(0),
    has_car(0),
    foorbar()         // do I need this line if "foobar" is std::string?
{ }

private:
    bool has_foo;
    bool is_bar;
    bool is_off;
    bool is_a_pony;
    bool has_car;
    std::string foobar;  
}

Question 1: Is there a way to do this simpler?

Question 2: Do I have to include the "foorbar" initializer in the list?

Upvotes: 2

Views: 381

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254431

Is there a way to do this simpler?

I guess you mean, is there a way to avoid initialising each bool individually? You could put them inside a structure, and value-initialise that:

Lorem() : flags() {}

private:
struct Flags {
    bool has_foo;
    bool is_bar;
    bool is_off;
    bool is_a_pony;
    bool has_car;
} flags;

or wrap them in something that forces value-initialisation

template <typename T> struct value_init {
    value_init() : value() {}
    T value;
};

value_init<bool> has_foo;

or perhaps use std::bitset or similar.

Do I have to include the "foorbar" initializer in the list?

No. That's a class type with a default constructor; that constructor will be used whether you explicitly value-initialise it, or leave it to be default-initialised.

Upvotes: 3

ForEveR
ForEveR

Reputation: 55887

No, there is no simpler way, by the way it's probably more clear to use false, instead of 0, when you initialize boolean variable.

There is no need of initialization of foobar, it will be constructed with default constructor, if you don't initialize it.

Upvotes: 3

slavik
slavik

Reputation: 1

class Lorem: public Ipsulum {
public:
Lorem() :
    has_foo(0),
    is_bar(0),
    is_on(0),
    is_a_pony(0),
    has_car(0),
    foorbar("")         // do I need this line if "foobar" is std::string?
{ }

it must works

Upvotes: -1

Related Questions