Diamond problem in CPP
Diamond problem explained
The basic scenario
a. Suppose P is the base class.
b .Class Q and R inherits from class P.
c. Class S inherits from both Q and R.
Now, if P has a member (like a variable or function), and S tries to access it, ambiguity arises: should it use the version inherited via Q or the one via R?
CPP Program:
#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 will solve it:
C++ solve this problem using virtual function which ensures that only one copy of the base class is shared.
Solved :
#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