1️⃣ Problem: Name Conflict in Constructor
When the constructor parameter has the same name as the class data member, it creates ambiguity.
✅ Solution: Use Member Initializer List with this->
to differentiate between them.
2️⃣ Syntax
class ClassName {
private:
int value; // Data member
public:
ClassName(int value) : value(value) { // No ambiguity
}
};
✅ The first value
is the data member.
✅ The second value
is the constructor parameter.
3️⃣ Example: Resolving Name Conflict
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
public:
// Using Member Initializer List to resolve name conflict
Student(string name, int age) : name(name), age(age) {
cout << "Name: " << this->name << ", Age: " << this->age << endl;
}
};
int main() {
Student s1("Alice", 20);
Student s2("Bob", 22);
return 0;
}
🔹 Output
Name: Alice, Age: 20
Name: Bob, Age: 22
✅ Why does this work?
✔ name(name)
→ The first name
refers to the class member, the second name
is the parameter.
✔ age(age)
→ The first age
refers to the class member, the second age
is the parameter.
✔ this->name
ensures clarity in the constructor body.
4️⃣ Example: Resolving Name Conflict for const
Members
#include <iostream>
using namespace std;
class Test {
private:
const int value; // Constant data member
public:
// Using Member Initializer List to initialize const member
Test(int value) : value(value) {
cout << "Value = " << this->value << endl;
}
};
int main() {
Test obj(100);
return 0;
}
🔹 Output
Value = 100
✅ Why is this necessary?
✔ const int value
must be initialized in the Member Initializer List.
✔ value(value)
ensures the constructor parameter assigns the value to the class member.
5️⃣ Example: Resolving Name Conflict in Inheritance
#include <iostream>
using namespace std;
class Base {
protected:
int id;
public:
Base(int id) : id(id) { // Resolving name conflict
cout << "Base ID = " << this->id << endl;
}
};
class Derived : public Base {
private:
string name;
public:
Derived(int id, string name) : Base(id), name(name) { // Resolving conflict
cout << "Derived Name = " << this->name << endl;
}
};
int main() {
Derived obj(101, "John");
return 0;
}
🔹 Output
Base ID = 101
Derived Name = John
✅ Key Takeaways:
✔ id(id)
resolves the conflict in Base
class.
✔ name(name)
resolves the conflict in Derived
class.
✔ Ensures clear and efficient initialization in inheritance.
6️⃣ Summary
✔ Use Member Initializer List to resolve name conflicts when the constructor parameter matches the data member.
✔ this->memberName
ensures clarity when needed inside the constructor.
✔ Required for const
and reference members.
Would you like an example with multiple inheritance? 🚀
0 Comments