1️⃣ What is a Member Initializer List?
A Member Initializer List in C++ is a way to initialize class members directly when the constructor is called, instead of assigning values inside the constructor body.
🔹 Why Use Member Initializer List?
✅ Faster execution (Directly initializes, avoiding extra assignment)
✅ Mandatory for const
and reference
members
✅ Preferred for initializing base class members in inheritance
2️⃣ Syntax of Member Initializer List
class ClassName {
private:
int value;
public:
ClassName(int val) : value(val) { // Member Initializer List
}
};
3️⃣ Example: Single Value Member Initializer List
#include <iostream>
using namespace std;
class Student {
private:
string name;
public:
// Using Member Initializer List
Student(string n) : name(n) {
cout << "Student Name: " << name << endl;
}
};
int main() {
Student s1("Alice"); // Object creation with initializer list
return 0;
}
🔹 Output
Student Name: Alice
4️⃣ Example: Initializing const
and Reference Members
#include <iostream>
using namespace std;
class Test {
private:
const int x; // Constant member
int &y; // Reference member
public:
// Member Initializer List is REQUIRED for const & reference
Test(int a, int &b) : x(a), y(b) {
cout << "x: " << x << ", y: " << y << endl;
}
};
int main() {
int num = 20;
Test obj(10, num); // Initializing object
return 0;
}
🔹 Output
x: 10, y: 20
✅ Why is Member Initializer List needed here?
✔ const int x
cannot be assigned later (must be initialized at declaration).
✔ int &y
must be initialized with a valid reference.
5️⃣ Key Takeaways
✔ Faster & more efficient than assigning inside the constructor body.
✔ Required for const
and reference members.
✔ Helps in better code readability & initialization.
Would you like an example with multiple initializations? 🚀
0 Comments