Uses of initializer List in C++

This tutorial will focus on when to use the initializer list in C++.

Initializer Lists in C++:

In C++, an initializer list is used to initialize a class’s data members.

It will begin after the constructor name and its parameters.

Initializer List begins with a semicolon and the variables after this along with their values.

Syntax:

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

C++ code showing Initializer List:

#include <bits/stdc++.h>
using namespace std;

class A
{
  private:
  int data;

  public:
  // Initializer List 
  A(int d):data(d)
  {
    cout << "The Value initialized is: " << data;
  }
};

int main()
{
  //initializing the object
  A obj1(50);
  return 0;
}

Output:

The Value initialized is: 50

 

Uses of initializer list:

1) For Initializing a data member of reference type:

When the reference type data member is to be initialized, then we will use an initialization list.

These reference types can only be initialized once and are immutable.

#include <bits/stdc++.h>
using namespace std;
 
class A
{
  private:
  int &r1;

  public:
  A(int &datamem):r1(datamem)
  {
    cout << "The value of reference type data member is: " << r1;
  }
};

int main()
{
  int r1=50;
  A obj1(r1);
  return 0;
}

Output:

The value of reference type data member is: 50

 

2) For Initializing a const data member:

The const data members can be initialized only once and that can be done in the initialization list.

#include <bits/stdc++.h> 
using namespace std;

class A
{
  private:
  const int x;

  public:
  A(int datamem):x(datamem)
  {
    cout << "The const value passed is: " << x;
  }
  
};

int main()
{
  A obj1(50);
}

Output:

The const value passed is: 50

3) For Initializing the objects that do not have default constructor:

When the parent class does not have a default constructor, then using this initializer list we can have that.

#include<iostream>
using namespace std;

class A_
{
  public:
  A_(int m)
  {
    cout <<"The constructor value is: "<< m << endl;
  }
};

class initializer_:public A_
{
  public:
  // This is the default constructor using initializer list
  initializer_():A_(50)
  {
    cout << "This is inside the Constructor of initializer list" << endl;
  }
};

int main()
{
  initializer_ obj1;
  return 0;
}

Output:

The constructor value is: 50
This is inside the Constructor of the initializer list

 

4) For Performance improvement:

Using an initializer list we can avoid the creation of temporary objects.

By this, we can improve the performance.

 

These are the uses of the initializer list.

Leave a Reply

Your email address will not be published.