Answer to Question #326256 in C++ for gayathri

Question #326256

Discuss various applications of Initializer List with the help of suitable examples


1
Expert's answer
2022-04-10T17:45:27-0400

#1) A Default Constructor is not Provided for the Member Object Class.

When we have another class object as the member of the class and the class of that object doesn’t have default constructor, then we initialize this data member object using the initializer list.


#include <iostream>
using namespace std;
 
class A {
   int i;
   public:
   A(int );
};
  
A::A(int val) {
   i = val;
   cout << "Constructor ::A ; i = " << i << endl;
}
  
class B {
   A a;
   public:
   B(int );
};
B::B(int val):a(val) {
   cout << "Constructor :: B";
}
  
int main() {
   B obj(10);
   return 0;

}


#2) Initializing Const Data Members.

As const data members can be initialized only once, we initialize them using the initializer list.


#include<iostream>
using namespace std;
class sample
{
   private:
   const int val;
   public:
   sample(int val):val(val)
   {
      cout << "Value is " << val;
   }
};
int main()
{
   sample obj(10);

}


#3) For Initializing Reference Data Types.


Like constants references are immutable. So whenever we need to initialize the reference type data members, we use initializer lists.


#include<iostream>
using namespace std;
class sample
{
   private:
   int &ref_val;
   public:
   sample(int &ref_val):ref_val(ref_val)
   {
      cout << "Value is " << ref_val;
   }
};
int main()   {
      int ref=10;
      sample obj(ref);
      return 0;

}


#4) When Member Name and Parameter have the same Name.

When member names of a class are to be initialized with the parameters and these parameters have the same names as member names, we use initializer list. In our previous topics, we used this pointer for the same situation. The second option is the initializer list.


#include <iostream>
using namespace std;
class Sample {
   private:
   int num;
   char ch;
   public:
   Sample(int num,char ch):num(num),ch(ch){
      cout<<"num = "<<num<<endl;
      cout<<"ch = "<<ch;
   }
  
};
int main(){
   Sample obj(100,'A');
  
   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS