Gluster Interview Question
Software Engineer / DevelopersYes, you can use the initialization list to initialize the normal (non-const, non-static) members. Infact, this is a more efficient way of initializing class members.
Other situations where you need to use the initialization list are:
1. Initializing references.
Class A;
Class B
{
private:
A& ref;
public
B(const A& ref): ref(ref)
{
}
}
2. Need to initialize some members of the parent class (if the parent class has a parameterized constructor).
3. Const members.
The const variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution. class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects. A const variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.
-HTH
This thing has been explained very nicely in Effective c++ by Scott Mayer. In the first case say
myclass(int a=10)
{
i = a; // Its assignment not initialization
}
Here First the default constructor is called and then the value is again assigned to i by calling the copy constructor, thus wasting the work done by default constructor. Initialization mean the value with which the variable is born. To ensure that we make use of member initialization list.
myclass(int a=10)::i(a)
{
// This is called initialization
}
This ensures that the variable is born with the given value. in previous case the value of constant was getting modified on being the copy constructor called. But the member initialization list solves that problem. This is very effective when we require to initialize the user defined data members.
Apart from initialsing constant variables, is there any scenario where we should be using class initialsiation list instead of constructors?
- xing2785 February 28, 2011Is it a proper method to use class initialsiation list instead of constructors for normal variables