C++ Tips and Tricks

Common source of mistakes:
  1. Initializing class members in an order different from the declaration order.


1. Initializing class members in an order different from the declaration order:

Consider the following scenario:
class MyClass{
private:
    int *fList;
    int fSize;
public:
    MyClass(int aSize) : fSize(aSize), fList(new int[aSize]) { ... }
};
This seemingly innocent code has a problem. The member fSize gets initialized after the fList is initialized. So, even if you tried to initialize fSize before fList, the C++ compiler will have its own way (because the standards say so). Always make a practice of initializing the class members in the order in which you declare them inside the class. This way, you will know with 100% probablity what all have been initialized and whether it is ok to use the members.

Updated by Chirag Dalal.