How does overload resolution work in the context of a private modifier?

I can not understand the output of the following C ++ snippet.

Should not be objc.fn()invoked A fn()since B fn()is privateand should not be visible at C. However, the answer is: the challenge is fn()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;
}
+1
source share
4 answers

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

At a very high level, a call to a named function can be handled as follows:

  • The name is scanned to form the initial overload set.

  • (, ).

  • , ( ) . .

  • , . , ; .

  • . , , .

, , , the call to fn() is ambiguous 4.

+4

:

class D {
    void fn1() {}
public:
    void fn2() {}
};

int main() {
    D d;
    d.fn2(); // Compiles fine
    d.fn1(); // Error: fn1 is private
}

, d.fn1() fn1 , , fn1 . B::fn C.

, . , , .

: fn ? , , , fn .

+2

, . , , , .

$ make pru
g++     pru.cc   -o pru
pru.cc: In function ‘int main()’:
pru.cc:15:8: error: request for member ‘fn’ is ambiguous
pru.cc:9:9: error: candidates are: void B::fn()
pru.cc:6:9: error:                 void A::fn()
make: *** [pru] Error 1

, , , A:: fn(). , , , ( B, - ).

+1

@songyuanyao.
++.

, :

  • , .
  • , .!!

Suppose access specifiers do not allow a function to participate in overload resolution, and then:

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(); // A::fn() is being invoked
  return 0;
}

Now we modify the code:

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

Nothing else was affected, and suddenly

objc.fn(); // B::fn() is being invoked

The subscriber of your function does not know that its basic function is no longer the same.
This is blasphemy!

To prevent all such failures, the standard committee adopted this design decision.

0
source

Source: https://habr.com/ru/post/1683663/


All Articles