Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

initializer
list
c++

What are initializer lists in C++?

Educative Answers Team

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters. The list begins with a colon ( : ) and is followed by the list of variables that are to be initialized – all of​ the variables are separated by a comma with their values in curly brackets.

Syntax

Constructorname(datatype value1, datatype value2):datamember(value1),datamember(value2)
{
    ...
}

Using an initialization list is almost identical to doing direct initialization (or uniform initialization in C++11).

Code

The following example uses an initializer list in the default constructor to set the value for the variable value of the class.

#include<iostream>
using namespace std;

class Base
{
  private:
  int value;
  public:
  // default constructor
  Base(int v):value(v)
  {
    cout << "Value is " << value;
  }
};

int main()
{
  Base myobject(10);
  return 0;
}

There are several cases where the use of an initializer list is absolutely necessary, these include:

1. Initializing a reference type data member

An initialization list is used to initialize a data member of reference type. Reference types can only be initialized once.

#include<iostream>
using namespace std;

class Base
{
  private:
  int &ref;
  public:
  Base(int &passed):ref(passed)
  {
    cout << "Value is " << ref;
  }
};

int main()
{
  int ref=10;
  Base myobject(ref);
  return 0;
}

2. Initializing const data member

const data members can be initialized only once, so they must be initialized in the initialization list.

#include<iostream>
using namespace std;

class Base
{
  private:
  const int var;
  public:
  Base(int constant_value):var(constant_value)
  {
    cout << "Value is " << var;
  }
};

int main()
{
  Base myobject(10);
}

3. Initializing member objects which do not have a default constructor

If you have a field that has no default constructor (or a parent class with no default constructor), then ​you must specify which constructor you wish to use.

#include<iostream>
using namespace std;

class Base_
{
  public:
  Base_(int x)
  {
    cout << "Base Class Constructor. Value is: " << x << endl;
  }
};

class InitilizerList_:public Base_
{
  public:
  // default constructor using initializer list
  InitilizerList_():Base_(10)
  {
    cout << "InitilizerList_'s Constructor" << endl;
  }
};

int main()
{
  InitilizerList_ mylist;
  return 0;
}

RELATED TAGS

initializer
list
c++
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring