diamond problem CPP(most asked in interview)
💎 Diamond Problem in C++ Explained
🔍 The Basic Scenario
- a. Suppose P is the base class.
- b. Class Q and R inherit from class P.
- c. Class S inherits from both Q and R.
Now, if P has a member (like a function), and S tries to access it, ambiguity arises: should it use the version from Q or from R?
⚠️ Problem Code (Ambiguous Inheritance)
#include <iostream>
using namespace std;
class A {
public:
void show() { cout << "A::show" << endl; }
};
class B : public A { };
class C : public A { };
class D : public B, public C { };
int main() {
D obj;
obj.show(); // ❌ Error: request is ambiguous
}
✅ How We Solve It
C++ solves the diamond problem using virtual inheritance, which ensures only one shared copy of the base class.
✅ Solved Version Using Virtual Inheritance
#include <iostream>
using namespace std;
class A {
public:
void show() { cout << "A::show" << endl; }
};
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };
int main() {
D obj;
obj.show(); // ✅ No ambiguity
}
Comments
Post a Comment