Dollarslice
Dollarslice

Reputation: 10324

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?

Upvotes: 1

Views: 1280

Answers (2)

Antoine
Antoine

Reputation: 5198

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).

Upvotes: 1

littleadv
littleadv

Reputation: 20282

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).

Upvotes: 2

Related Questions