Alex Rivera | Logout

C++ class initialisation containing class variable initialization

Asked 2008-10-02T10:25:29.800
13

I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets?

DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent )
    : QGraphicsScene( screenRect, parent ),
    myParent( parent ), 
    slideUndoImageCurrentIndex(-1),
    nextGroupID(0),
    m_undoInProgress(false),
    m_deleteItemOnNextUndo(0)
    line(0),
    path(0)
{
    /* Setup default brush for background */
    scDetail->bgBrush.setStyle(Qt::SolidPattern);
    scDetail->bgBrush.setColor(Qt::white);
    setBackgroundBrush(scDetail->bgBrush);

}
Edit
Report

3 Answers

2

Because, in the constructor's body ("within the curly brackets") the member variables are already default-constructed. That may have some performance implications, when you have a member variable of a type that has non-trivial construction, when you first have it default-constructed and then you assign it some other value in the constructor, when you could have custom-construct it directly.

Also, some types may not be default-constructed (for example references) and must be constructed in the initialization list.

answered 2008-10-02T10:37:02.317
2

If you have const variables, their value can not be set via assignment.

The initialization is also a bit more efficient when assigning values to objects (not built-ins or intrinsics) as a temporary object is not created like it would be for an assignment.

See C++ FAQ-Lite for more details

answered 2008-10-02T10:41:45.113
0

Greg Hegwell's answer contains some excellent advice, but it doesn't explain why the compiler is generating a warning.

When the initializer list of a constructor is processed by the compiler, the items are initialized in the order they are declared in the class declaration, not in the order they appear in the initializer list.

Some compilers generate a warning if the order in the initializer list is different from the declaration order (so you won't be surprised when items are not initialized in the order of the list). You don't include your class declaration, but this is the likely cause of the warning you're seeing.

The rationale for this behavior is that the members of a class should always be initialized in the same order: even when the class has more than one constructor (which could have the members ordered differently in their initializer lists).

answered 2010-05-06T16:39:59.160

Your Answer