Initializer List

Let us understand the concept of initializer list in C++ with the help of an example.

Consider a class viz. person, which has data members like age, name and employee data
Example

#include <iostream>
#include <string>
using namespace std;
class employeeData {
unsigned int m_salary;
public:
employeeData() {
cout << “employeeData default C’tor” << endl;
m_salary = 0;
}
employeeData(unsigned int salary) {
cout << “employeeData parameterized C’tor” << endl;
m_salary = salary;
}
employeeData(const employeeData& data) {
cout << “employeeData Copy C’tor” << endl;
m_salary = data. m_salary;
}
employeeData& operator=(const employeeData& data) {
cout << “employeeData assignment operator” << endl;
if (this == &data) {
return *this;
}
m_salary = data. m_salary;
}
};
class person {
unsigned int m_age;
string m_name;
employeeData m_data;
public:
person(unsigned int age, char* name, employeeData& data) {
m_age = age;
m_name = name;
m_data = data;
}
void displayInfo() {
cout << “Person Details: “ << endl;
cout << “Name: “ << m_name << “ Age: “ << m_age << “

Salary: “ << m_data.m_salary << endl;
}
};
//Main function
int main() {
employeeData data(10000);
person p1(40, “Vikas”, data);
p1.displayInfo();
return 0;
}


Output:

Now, when object p1 is created, person constructor is called. In the person constructor, two things happen for employeeData data member.

1. employeeData object m_data is created i.e. default constructor of employeeData is called.

2. Value is assigned to the m_data using assignment operator i.e. assignment operator of employeeData class is called.
The above behavior happens for string (m_name) data member as well.

The above two calls can be converted in to single call using initializer list.

Below is the same program using initializer list.

#include <iostream>
#include <string>
using namespace std;
class person {
unsigned int m_age;
string m_name;
public:
person(unsigned int age, string name, employeeData& data):

m_age(age), m_name(name), m_data(data) { //Initializer List
}
void displayInfo() {
cout << “Person Details: “ << endl;
cout << “Name: “ << m_name << “ Age: “ << m_age << “
Salary: “ << m_data.m_salary << endl;
}
}
//Main function
int main() {
employeeData data(10000);
person p1(40, “Vikas”, data);
p1.displayInfo();
return 0;
}


Output:

Using initializer list, now only the copy constructor of employeeData is called instead of default constructor and assignment operator.

Using initializer list, we can improve the performance of our program by reducing number of calls to one.

NOTE: This behavior is not applicable for primitive data types i.e. for primitive data types, there is no advantage in initializing using initializer list as far as performance is concerned.






Related posts