Multiple Value Member Initializer List in C++

 


1️⃣ What is a Member Initializer List?

A Member Initializer List allows us to initialize multiple class members before the constructor body executes, leading to better efficiency.

🔹 Why Use Multiple Value Member Initializer List?

Faster than assigning inside the constructor
Supports const and reference members
Ensures initialization order


2️⃣ Syntax of Multiple Value Member Initializer List

class ClassName {
private:
    int a;
    double b;
    string c;

public:
    ClassName(int x, double y, string z) : a(x), b(y), c(z) {  
        // Constructor body (optional)
    }
};

3️⃣ Example: Initializing Multiple Values

#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int age;
    double marks;

public:
    // Using Member Initializer List for multiple variables
    Student(string n, int a, double m) : name(n), age(a), marks(m) {
        cout << "Name: " << name << ", Age: " << age << ", Marks: " << marks << endl;
    }
};

int main() {
    Student s1("Alice", 20, 89.5);
    Student s2("Bob", 22, 76.0);

    return 0;
}

🔹 Output

Name: Alice, Age: 20, Marks: 89.5
Name: Bob, Age: 22, Marks: 76.0

4️⃣ Example: Initializing const and Reference Members

#include <iostream>
using namespace std;

class Test {
private:
    const int x;  // Constant member
    int &y;       // Reference member
    double z;     // Regular member

public:
    // Member Initializer List for multiple members
    Test(int a, int &b, double c) : x(a), y(b), z(c) {
        cout << "x: " << x << ", y: " << y << ", z: " << z << endl;
    }
};

int main() {
    int num = 50;
    Test obj(10, num, 25.5);

    return 0;
}

🔹 Output

x: 10, y: 50, z: 25.5

Why is Member Initializer List required?
const int x must be initialized at declaration.
int &y requires a reference to an existing variable.


5️⃣ Key Takeaways

Multiple variables can be initialized at once, improving efficiency.
Required for const and reference members.
✔ Ensures variables are initialized in the order they are declared in the class.

Would you like an example with inheritance and initializer lists? 🚀

Post a Comment

0 Comments