on Leave a Comment

C++ Initializer List

Initializer list is used for initializing data members of a class. We can also initialize data members of class using constructor. But there is some situations, when we need initializer list. Initializer list is written with constructor. 

For Example:

class A
{
private:
  int x, y, z;
public:
  A(int a, int b, int c): x(a), y(b), z(c)
  {}
};

Initializer list is followed by colon (:) and each data members is separated by commas. 

Why we need initializer list?

(a) To initialize non-static const data members

It is necessary to initialize const variable, when it is declared. But, we can't initialize const variables in constructor. So, we need initializer list.

For Example: 

#include<iostream>
using namespace std;
class A
{
private:
  int x, y, z;
  const int t;
public:
  A(int a, int b, int c, int d): x(a), y(b), z(c), t(d)
  {   }
  void show()
  {
      cout<<"x = "<<x<<endl;
      cout<<"y = "<<y<<endl;
      cout<<"z = "<<z<<endl;
      cout<<"t = "<<t<<endl;
  }
};
int main()
{
    A o1(1, 2, 3, 4);
    o1.show();
    return 0;
}

OUTPUT:

x = 1
y = 2
z = 3
t = 4

(a) To initialize reference members

It is necessary to initialize reference members, when it is declared. We can't initialize reference variables through constructor, but we can initialize reference variables through initializer list.

For Example:

#include<iostream>
using namespace std;
class A
{
private:
  int x, y, z;
  int &t;
public:
  A(int a, int b, int c, int &d): x(a), y(b), z(c), t(d)
  {   }
  void show()
  {
      cout<<"x = "<<x<<endl;
      cout<<"y = "<<y<<endl;
      cout<<"z = "<<z<<endl;
      cout<<"t = "<<t<<endl;
  }
};
int main()
{
    int i = 10;
    A o1(1, 2, 3, i);
    o1.show();
    return 0;
}

OUTPUT:

x = 1
y = 2
z = 3
t = 10

0 comments:

Post a Comment