1

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?

Dollarslice
  • 9,917
  • 22
  • 59
  • 87
  • Looking at your code on your previous question, I think you need to change your taste. You shouldn't prefer a long list of initializations in the body of the constructor, over a long initializer list. OK, so `x(y),` is a bit of an acquired taste when you're used to `x = y;`, but like you say that's how it's done. – Steve Jessop Nov 08 '11 at 11:00

2 Answers2

2

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

littleadv
  • 20,100
  • 2
  • 36
  • 50
  • If I place a constant in the header file such as this: const int BLAH = 1; I get an error, so I assumed I had to put them in the initialiser list, which did in fact silence the compiler. Is this wrong? – Dollarslice Nov 08 '11 at 10:30
  • and are you saying then that instance members of class types DO always have to be in the initialiser list UNLESS they have a default constructor? – Dollarslice Nov 08 '11 at 10:31
  • @SirYakalot - for your first question I'm not sure I can answer without actually seeing the code. For your second question - unless you have default values for your parameters, you'll get `error: no matching function for call to ‘classname::classname()` from your compiler. Note - this is for **your own classes**. Built in types and most of the STL classes have default constructors. – littleadv Nov 08 '11 at 18:16
1

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

Community
  • 1
  • 1
Antoine
  • 5,158
  • 1
  • 24
  • 37