Derivatives and base conversion and friendship

From C ++ Primer 5th edition (D inherits from B)

Member functions and friends of classes derived from D can use the tobase derivative transformation if D inherits from B, using either open or protected. such code cannot use conversion if D inherits privately from B.

Is there any reason for this or should I take it at face value? It may seem obvious why this happens, but it turns me off in one example:

#include <iostream>
using namespace std;

class Base { 
public: 
    int x = 2;
};

class Derived : protected Base { };

class DerivedAgain : public Derived {
    friend void test();
};

void test() {
    ??? a;
    Base* p = &a;
    cout << p->x;
}

int main(){
    test();
}

I want to understand test()member accessibility xin base-based transformations. Considering three potential cases of type ???of ain function test().

  • ???- Base. xis a public member Base. In this case there is no problem.
  • ??? - DerivedAgain. Derived-to-Base , test() friend DerivedAgain, , Base. x.
  • ??? - Derived. . ? . test() Derived, p->x , , Derived-to-Base ? , ?

, test()

void test() {
    Derived a;
    cout << a.x;
}

, , x, Derived, protected , , .

a Base DerivedAgain, test() , .

, , .

+4
1

, . , , , [class.access.base] N4527:

B of N R,
- B N,
- R N, B N,
- R P, N, B P,
- S , B S, R, S N R.

. R (test) P (DerivedAgain), N (Derived), B (Base) P (DerivedAgain).

, gcc ( 67493), , clang - TC , (CWG # 1873). , . , , gcc ( ), clang ( CWG # 472) .

, . ++.

+7

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


All Articles