When is it nesessary with initialize list

T

Tony Johansson

Hello!!

Hello Experts!

I'm right if I say that if I have attribute that is constant or attribute
that is of reference type or attribute that is class type then I must use
initialize list.

//Tony
 
H

Howard

Tony Johansson said:
Hello!!

Hello Experts!

I'm right if I say that if I have attribute that is constant or attribute
that is of reference type or attribute that is class type then I must use
initialize list.

//Tony

If the member variable (what you've called "attribute") is a class object,
then you _can_ initialze it via the member initializer list, but you don't
_have_ to. If it exists, or can be generated by the compiler then, the
default constructor for the contained class object will be called during
construction of the containing class. But if there is no default
constructor, or if the compiler is unable to generate one (because you've
declared one or more constructors yourself), then yes, you will need to
construct it via the member initializer list. (And you may want to, anyway,
since it's the only way to pass parameters to that object's constructor.)

-Howard
 
V

Victor Bazarov

Tony said:
I'm right if I say that if I have attribute that is constant or attribute
that is of reference type or attribute that is class type then I must use
initialize list.

If your const "attribute" is of class type that has a default c-tor, then
you don't have to, if default-initialisation is OK for it. Of course, in
many cases default initialisation is not OK, then you need to initialise
it in the constructor initialiser list. References need to always be
explicitly initialised.

There is a pitfall in all that. If you have a member _array_ of some type
that doesn't have a default c-tor, there is no way to initialise it in the
constructor initialiser list, const or non-const.

V
 
K

Karl Heinz Buchegger

Tony said:
Hello!!

Hello Experts!

I'm right if I say that if I have attribute that is constant or attribute
that is of reference type or attribute that is class type then I must use
initialize list.

You are right with the first 2 but the third case is different. Depending
on the exact configuration of constructors it is possible to let the
compiler use the default constructor for the initialization and later
on assign in the constructor.

But you get it backwards.

You *should* use initializer lists until there is no way to do
what you want with an initializer list (eg. initializing
an array)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top