C++ Programming Concepts - When is an Initialization List Compulsory?
When is an Initialisation List Compulsory?
Having an initialization list in a constructor is a good programming practice, since the absence of an initialization list will mean that it's not initialization but assignment which is taking place inside the body of the constructor. That is because the memory has already been allocated before the first statement of the constructor is executed.
Writing an initialization list is generally optional. But there are cases where the Initialization List is compulsory.
Case I: When the class has a const member.
Variables which are const cannot be assigned values, they have to be initialized with a value as soon as they are created. A declaration statement in a function creates the const, so we have to assign a value to the const in the declaration statement itself. However, when a class has a const data member, it can't be initialized in the class declaration - no objects are created yet, and class is just a data type. Thus, the initialization list becomes compulsory since absence of initialization list would mean assignment which is not allowed for const variable. Thus, if the initialization list is not present, the code will not compile.
Case II: When the class has a reference member.
When a class has a reference member, which is just a reference to another variable, the initialization list is compulsory. The reference, as soon as it's created, needs to know what is it referring to, and that is only possible for a class reference member if it's put in the initialization list.
Case III: When the base class does not have a non-parameterized constructor.
At the time of the creation of an object, the constructor is automatically invoked, which in turn invokes the base class constructor. If the initialization list is not present, the constructor of the derived class invokes the non-parameterized constructor of the base class, but in case the base class has only parameterized constructor, than this would result in an error. Thus, we have to explicitly specify the parameterized constructor, with required parameters, and this can be done only in an initialization list.
In any of the above cases, if initialization list is absent, then you'll get a compilation error as soon as you try to instantiate the class - which means when you try to create an object of the class.
The program above was getting compiled before the initialization list was commented out. In the absence of the initialization list, the program gave this error on compilation:
uninitialized member "CompulsoryInitList::k" with "const" type "const int"