views:

152

answers:

2

Hi

I was told there are multiple situations in which initialization list must be used to for initialization.

There are three cases

1) const member

2) reference

3) members without default constructors

Is that right? Anyone would like elaborate this? Is there any other case I missed?

Thanks!

A: 

Yes you are right .

It is also used to initialize base class data members in case of inheritance.

Ashish
how about static member?
skydoor
initialization of static member should de done at time of its definition or use static function to do so rather that initialization list.
Ashish
+2  A: 

...or POD class types or arrays of POD class types that directly or indirectly themselves contain a const-qualified member. But yes, yours are the main cases.

For your (3), this only applies if there are user-declared constructors other than a default constuctor. If there are no user-declared constructors at all then the member can be default initialized if it isn't mentioned in the initializer list.

Charles Bailey
can you show me one example code for the case 3? Thanks so much!
skydoor
What do you mean? Code that compiles with a member of class type that doesn't have any constructors or code that doesn't because the class type has a non-default constructor?
Charles Bailey
I think the code that doesn't because the class type has a non-default constructor?
skydoor
`struct S { S(int); }; struct T { S s; T() {} };`
Charles Bailey