I faced a problem recently with a 3rd party library which generates classes from a xml. Here is a gist of it:
class B;
class A
{
void doSomething();
friend class B;
};
class B
{
void doSomething();
void doSomethingMore()
{
doSomething();
}
};
The compiler flags call to the function doSomething() as ambiguous and flags it as an compiler error. It is easy to understand why it gives the error.Class B being friend of class A, every member of class B has access to all the members of class A. Renaming of the either of functions resolved my problem but it got me thinking that shouldn’t in this case the compiler should give a priority to the class’s own member function over the function in another class of which it is a friend?
Note: I will update the compiler version details tomorrow..Need to check the exact version details at the workplace. I guess i should have got them in first place..:(
[Problem Update & Resolution]
I checked out again with a small sample program and my bad the problem is not with the ambiguity due to friend functions. The 3rd party library internally generates a function with the same signature and inside the same class which causes the ambiguity. Thanks for the replies, at least my misconception got corrected 🙂
There is no ambiguity. The function called in A requires an A instance. The function called in B requires a B instance.
doSomethingMore is called on a B instance and therefore the function that gets called is the one in B.
You seem to have misunderstood friendship. All it means is that, in this case, given an instance of A, member functions of B can call the A::doSomething() function or do anything else in A that has private access.