Interview question.

G

Guest

Name two cases where you MUST use initialization list as opposed to
assignment in constructors.
 
V

Victor Bazarov

?? said:
Name two cases where you MUST use initialization list as opposed to
assignment in constructors.

Think of what cannot be constructed without initialisation. What do
you initialise in the initialisation list? Base classes and members,
right? So, what would require a class to be placed in the initialiser
list? What would require a member to be placed there?

V
 
A

Alf P. Steinbach

* Jim Langston:
References and Base Classes are two.

Language level technical reasons:

1. Base classes.
2. Member variables with user-defined constructors.
3. Member variables with inaccessible or inappropriate assignment operator.
4. "const" member variables.
5. Reference members.

Other technical reasons:

6. When there are dependencies between member variables so that
some must be initialized before one where 1...5 applies.

Non-technical reasons:

7. When the coding guideline or other authority says so.
 
A

Alf P. Steinbach

* Ron Natalie:
Actually, just those missing a default constructor.

Actually, at that level of detail it's those with inaccessible or
missing default constructor.

:)


Alf (superior nit-picker)
 
G

Gianni Mariani

Alf said:
* Jim Langston:

Language level technical reasons:

1. Base classes.
2. Member variables with user-defined constructors.
3. Member variables with inaccessible or inappropriate assignment operator.
4. "const" member variables.
5. Reference members.

Other technical reasons:

6. When there are dependencies between member variables so that
some must be initialized before one where 1...5 applies.

Non-technical reasons:

7. When the coding guideline or other authority says so.

Number 8 is a "meta" reason for meta programming.

8. When initializing an member of a template class that you cannot
determine what type it will be because not doing so will result in
potential problems either with uninitialized POD's.

i.e.

template <typename T> struct X
{
T v;
X() : v() {}
};

X<int> i; // i.v is initialized to zero
X<std::string> s; // s.v is initialized to ""

I suppose it's not really a MUST ...
 

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
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top