简体   繁体   中英

Initializing data members inside class body

When data members should be initialized directly inside class/struct body over using constructor?

struct A{
    int x;
    A() : x{3} {}
};

struct B{
    int x{3};
};

The above two methods have the same effect.

Member init list must be used if the value depends on a constructor argument. It must also be used if separate constructors should initialise the member with different value. It must also be used prior to C++11, because that is the language version where the default member initialisers were introduced.

Otherwise the choice is up to the programmer. Default member initialisers are useful for avoiding repetition in constructors that initialise with the same, constant value, as well as having more concise and simpler syntax.

I would like to point out one difference.

struct B{
    int x{3};
};

The above initialization applies to all the constructors where x is not explicitly initialized.

The below initialization applies ONLY to the default constructor. So if you are following below approach, you may end up with lot of boiler plate code when the value initialized is same.

struct A{
    int x;
    A() : x{3} {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM