1️⃣ Why Use Member Initializer List for const
Variables?
A const
variable in a class must be initialized at the time of object creation, and it cannot be assigned later.
✔ Member Initializer List is required because we cannot modify const
values inside the constructor body.
✔ Prevents accidental modification after initialization.
2️⃣ Syntax
class ClassName {
private:
const int value; // Constant member
public:
ClassName(int v) : value(v) { // Member Initializer List
}
};
3️⃣ Example: Initializing a const
Variable
#include <iostream>
using namespace std;
class Test {
private:
const int x; // Constant variable
public:
// Member Initializer List to initialize const variable
Test(int val) : x(val) {
cout << "x = " << x << endl;
}
};
int main() {
Test obj(10); // Initializing const member
return 0;
}
🔹 Output
x = 10
✅ Why is Member Initializer List needed here?
✔ const int x
cannot be assigned inside the constructor body, so we initialize it in the initializer list.
4️⃣ Example: Initializing Multiple const
Members
#include <iostream>
using namespace std;
class Constants {
private:
const int a;
const double b;
public:
Constants(int x, double y) : a(x), b(y) {
cout << "a = " << a << ", b = " << b << endl;
}
};
int main() {
Constants obj(5, 3.14);
return 0;
}
🔹 Output
a = 5, b = 3.14
5️⃣ Example: Initializing const
in Derived Class (Inheritance)
#include <iostream>
using namespace std;
class Base {
protected:
const int baseValue;
public:
// Initializing const in Base class
Base(int val) : baseValue(val) {
cout << "Base Value = " << baseValue << endl;
}
};
class Derived : public Base {
private:
const int derivedValue;
public:
// Initializing const in both Base and Derived classes
Derived(int b, int d) : Base(b), derivedValue(d) {
cout << "Derived Value = " << derivedValue << endl;
}
};
int main() {
Derived obj(10, 20);
return 0;
}
🔹 Output
Base Value = 10
Derived Value = 20
✅ Key Points:
✔ const baseValue
is initialized in Base class initializer list.
✔ const derivedValue
is initialized in Derived class initializer list.
6️⃣ Key Takeaways
✔ Member Initializer List is required for const
variables because they cannot be modified later.
✔ Ensures efficiency & proper initialization.
✔ Works in both single and multiple inheritance scenarios.
Would you like an example with reference members (&
) and const
together? 🚀
0 Comments