Uses of member initialization list:
Initialization list is used if class contains non static constant members because we can not initialize the constant members inside the constructor.
class demo
{
public:
const int i;
int j;
demo( ):i(10)
{
j = 20;
}
};
-----------------------------------------------------------------------------------
We can use parameterised constructor for initializing the members using member initialization list.
class demo
{
public:
int i,j;
demo(int x, int y):i(x),j(y)
{
}
};
int main()
{
demo obj(10,20);
printf("%d%d",obj.i,obj.j);
//10 20
return 0;
}
-----------------------------------------------------------------------------------
If we use member initialization list as well as we initialize inside the constructor then the value which is initialized insisde the constructor is considered as a final value.
class demo
{
public:
int i,j;
demo(int x, int y):i(x),j(y)
{
i = 30;
j = 40;
}
};
int main()
{
demo obj(10,20);
printf("%d%d",obj.i,obj.j);
// 30 40
return 0;
}
-----------------------------------------------------------------------------------
If a class contains Reference members then it must be initialized using Initializer List.
class demo
{
public:
int &i;
demo(int x): i(x)
{
}
};
int main()
{
int a = 10;
demo obj(a);
printf("%d",obj.i);
return 0;
}
-----------------------------------------------------------------------------------
In case of member initialization list members are initialized in order in which they are declared in class.
class demo
{
public:
int i,j,k;
demo(int x):j(++x),i(++x),k(x)
{
}
};
int main()
{
demo obj(10);
printf("%d%d%d",obj.i,obj.j,obj.k);
//11 12 12
return 0;
}
-----------------------------------------------------------------------------------
For initialization of member objects which do not have default constructor
class base
{
int i;
public:
base(int arg)
{
i = arg;
printf("Base constructor");
}
};
class demo
{
base a;
public:
demo(int x):a(x)
{
printf("Demo constructor");
}
};
int main()
{
demo obj(10);
return 0;
}
output:
Base constructor
Demo constructor
-----------------------------------------------------------------------------------
No comments:
Post a Comment