Initializer List | C++

/Initializer List | C++

Initializer list is used to initialize data members. The syntax begins with a colon(:) and then each variable along with its value separated by a comma. The initializer list does not end in a semicolon.

Syntax

ConstructorName(datatype value1, datatype value2):datamember(value1),datamember(value2)
{
  // Other Code
}

 

Example

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

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

 

Delegating constructor

If the name of the class itself appears as class-or-identifier in the member initializer list, then the list must consist of that one member initializer only; such constructor is known as the delegating constructor, and the constructor selected by the only member of the initializer list is the target constructor. In this case, the target constructor is selected by overload resolution and executed first, then the control returns to the delegating constructor and its body is executed. Delegating constructors cannot be recursive.

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int)
};

 

Uses of Initializer List

There are situations where initialization of data members inside constructor doesn’t work and Initializer List must be used. Following are such cases:

  • When no Base class default constructor is present
    In Inheritance base class constructor is called first, followed by the child class constructor.

    class Base_
    {
      public:
      // parameterized constructor
      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_ il;
        return 0;
    }

     

  • For initializing const data member, reference type.
    #include<iostream>
    using namespace std;
    
    class Base
    {
      private:
      int &ref;
      const int c_var;
      public:
      Base(int &ref, int c_var):ref(ref), c_var(c_var)
      {
        cout << "Value is " << ref;
      }
    };
    
    int main()
    {
      int ref=10;
      Base il(ref, 11);
      return 0;
    }

     

  • For improving performance
    If you are assigning the values inside the body of the constructor, then a temporary object would be created which will be provided to the assignment operator. The temporary object will be destroyed at the end of the assignment statement. Creation of temporary object can be avoided by using initializer list.
September 11th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of