Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

c++ - How does overload resolution work in the context of private modifier?

I am unable to understand the output of the following C++ snippet.

Should not objc.fn() call A's fn() since B's fn() is private and should not be visible in C. However, the answer is: the call to fn() is ambiguous. How?

#include<iostream>
using namespace std;

class A{
  public:
   void fn() { cout << "1"; }
};
class B{
   void fn() { cout << "2"; }
};
class C: public A, public B {};

int main(){
  C objc;
  objc.fn();
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to the book C++ Templates: The Complete Guide Appendix B.1,

At a very high level, a call to a named function can be processed in the following way:

  1. The name is looked up to form an initial overload set.

  2. If necessary, this set is tweaked in various ways (for example, template deduction occurs).

  3. Any candidate that doesn't match the call at all (even after considering implicit conversions and default arguments) is eliminated from the overload set. This results in a set of so-called viable function candidates.

  4. Overload resolution is performed to find a best candidate. If there is one, it is selected; otherwise, the call is ambiguous.

  5. The selected candidate is checked. For example, if it is an inaccessible private member, a diagnostic is issued.

As you can see, the access authority is checked at last, so the call to fn() is ambiguous will be reported firstly at step #4.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...