DEV Community

Cover image for When to use initializer list
Sakshi
Sakshi

Posted on

When to use initializer list

  • Define non static constant data member
const int x;
Base(): x{0} {}
//also this works
Base(int y): x(y) {}
Enter fullscreen mode Exit fullscreen mode
  • If you want to initialise reference variable then you can't initialise it without initialization list.
int& _x;
base(int x) : _x{x} {}
//base(int x): {_x = x};
Enter fullscreen mode Exit fullscreen mode
  • You can not initialize one class data member in another class if base class does not have default constructor
class base{
int _x;
public: 
base(){}
base(int x): _x{x} {}
};

class derive{
base b; //we are here calling default constructor of base as no //parameter passed
public:
derived(base x) {b = x;} //called first, copy constructor called from here

};
Enter fullscreen mode Exit fullscreen mode
  • You can not initialize base class data member from child class without initializer list
class base{
int _x;
public: 
base(int x): _x{x} {}
}

class derived : public base{
int _y;
public:
derived(int x,int y): base{x}, _y{y} {}
//base{x} calls constructor of base class
/* this is not gonna work, _x is private here
so you must use intializer list
derived(int x, int y){
_x = x;
_y = y;
}  
*/


};

int main(){
derived d(4,5);
return 0;
}
Enter fullscreen mode Exit fullscreen mode
  • You have temp variable same as data member
  • You can not initialize data member with same name as temporary variable without initializer list
class base{
int _x;
public:
base(int _x): _x{_x} {}

//base(int _x) { _x = _x; } there is errorneous

};
Enter fullscreen mode Exit fullscreen mode
  • Using initializer list optimize you code a little more

Image description

Image description

Top comments (0)