I know the diamond problem and method to solve it using virtual base class. I tried to solve diamond problem in a different way but did not succeed. I don't know why.
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "successfully printed";
}
};
class B: public A
{
};
class C: private A // display() of A will become private member of C
{
};
class D: public B, public C // private member display() of C should not be inherited
{
};
int main()
{
D d;
d.display();
return 0;
}
As the private members are not inherited the class D will not inherit any function from C, and when class D inherit class B and C, there should only 1 display() function in D. But when I try to access display()
function using object of class D, it is showing same problem that display function is ambiguous.
"Private members are not inherited" is a false premise, this isn't Java.
Member access in C++ was designed in such a way that if you replace any private: with public:, the behavior of the program will not change.
Because of that, name lookup, which occurs here when the compiler encounters the name "display" in d.display(), first locates all member functions in d with that name (there are two), then finds the best match (failure here), and only then checks if it happens to be inaccessible due to member access rules.
来源:https://stackoverflow.com/questions/26740893/overcoming-diamond-ambiguity-in-different-way