简体   繁体   中英

class instance member initialisation

If a class has an instance member that is itself a class, does the constructor ALWAYS have to provide an initialisation for it in the constructor initialiser list?

In some cases in my code this leads to very long initialiser lists, is this the way to do things? I only ask because it looks inelegant, but if it's how it's done then that's fine.

is the same also the case for constant instance member variables?

If you have a default constructor (without parameters) - then you don't need to explicitly initialize it.

For constant instances, there's no point in having default initialization, is there? So it wouldn't make sense to have them at all, unless you have something to initialize them with. (But it is of course possible, if for whatever reason that's what you're doing).

For objects , you will have to initialize all members that do not have a default constructor . If you omit a member in the initialization list, its default constructor will be used (or its value will be undefined for primitive types).

For primitive types ( int , pointers ), it is legal not to initialize them, but their value will be undefined .

Finally, you must initialize references to other objects ( std::string& ).

See this answer for more.

Additionally, I'd like to point out that if your class has many members, it may be a sign that you should split it into several smaller classes. The best practice is to have classes which only have one responsibility (see single responsibility principle ).

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