Main Content

Member not initialized in constructor

Constructor does not initialize some members of a class

Description

This defect occurs when a class constructor has at least one execution path on which it does not initialize some data members of the class.

The defect does not appear in the following cases:

  • Empty constructors.

  • The non-initialized member is not used in the code.

Risk

The members that the constructor does not initialize can have unintended values when you read them later.

Initializing all members in the constructor makes it easier to use your class. If you call a separate method to initialize your members and then read them, you can avoid uninitialized values. However, someone else using your class can read a class member before calling your initialization method. Because a constructor is called when you create an object of the class, if you initialize all members in the constructor, they cannot have uninitialized values later on.

Fix

The best practice is to initialize all members in your constructor, preferably in an initialization list.

Examples

expand all

class MyClass {
public:
    explicit MyClass(int);
private:
    int _i;
    char _c;
};

MyClass::MyClass(int flag) {
    if(flag == 0) {
        _i = 0;
        _c = 'a';
    }
    else {
        _i = 1;
    }
}

In this example, if flag is not 0, the member _c is not initialized.

The defect appears on the closing brace of the constructor. Following are some tips for navigating in the source code:

  • On the Result Details pane, see which members are not initialized.

  • To navigate to the class definition, right-click a member that is initialized in the constructor. Select Go To Definition. In the class definition, you can see all the members, including those members that are not initialized in the constructor.

Correction — Initialize All Members on All Execution Paths

One possible correction is to initialize all members of the class MyClass for all values of flag.

class MyClass {
public:
    explicit MyClass(int);
private:
    int _i;
    char _c;
};

MyClass::MyClass(int flag) {
    if(flag == 0) {
        _i = 0;
        _c = 'a';
    }
    else {
        _i = 1;
        _c = 'b';
    }
}

Result Information

Group: Object oriented
Language: C++
Default: Off
Command-Line Syntax: NON_INIT_MEMBER
Impact: Medium

Version History

Introduced in R2015b