Search code examples
c++qtclassmember-initialization

Should Qt class data members of a C++ class be initialized before being used?


There are many C++ programming best practices that are proposed in many articles and books. Following is a subset that is related to C++ class data members:

  1. Make sure that objects are initialized before they are used.
  2. Make sure that all constructors initialize everything in the object.
  3. It is usually more effective to initialize data members in the initializer list of each constructor than in its body.
  4. In the initializer list, data members should be listed in the order they are declared.

Consider the following class with data members of Qt class types:

class MyClass {
public:
    myClass();
    ~myClass();
private:
    int myInt;
    QString myQString;
    QList<QString> myQList;
    QHash<int, QString> myQHash;
    char * pChar;
};

By applying the above best practices, the constructor code would look like the following:

MyClass::MyClass() :
    myInt(0),    // OK, primitive should be initialized.
    myQString(),    // Is this really needed?
    myQList(),     // Is this really needed?
    myQHash(),    // Is this really needed?
    pChar(NULL)    // OK, pointer should be initialized.
{
}

However, I have the impression that not all of the Qt class data members need to be initialized. But I am not 100 % sure of this. Some developers argue that by putting all the data members in the initialization list, we may avoid omitting the initialization of some important data members that should be initialized. However, if this is a real concern, I would prefer putting a comment line for each data member that does not need to be initialized, for example:

MyClass::MyClass() :
    myInt(0), 
    //myQString(),
    //myQList(),
    //myQHash(),
    pChar(NULL) 
{
}

To summarize, I would like to know when a Qt class data member should be initialized, and when the initialization is not needed, and why. Thanks!


Solution

  • If you don't have a default constructor of a class then you must initialize it in initializer list, and it is not required to call default constructor in initializer list. It is not Qt specific it is a general rule for any class. When you have a default constructor(which takes 0 argument) even if you don't call it in initializer list, it will be called automatically.

    Update:

    Q1: Are the 2 versions of MyClass::MyClass() above equivalent? That is, do they produce 2 objects of same content?

    Yes.

    Q2: Is one version faster than the other?

    You can type the second version faster ;-), there is no performance difference.