Reputation: 27385
The following code I've written to check pointer conversion:
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class A
{
friend class B;
};
class B : private A { };
int main()
{
B *b = new B;
A *a = b;
cout << b << endl;
cout << a;
}
Section 11.2/4 N3797 says:
A base class B of N is accessible at R, if
— an invented public member of B would be a public member of N, or
— R occurs in a member or friend of class N, and an invented public member of B would be a private or protected member of N, or
— R occurs in a member or friend of a class P derived from N, and an invented public member of B would be a private or protected member of P, or
— there exists a class S such that B is a base class of S accessible at R and S is a base class of N accessible at R
I think A
is accessible base class of B
.
A prvalue of type “pointer to cv D”, where D is a class type, can be converted to a prvalue of type “pointer to cv B”, where B is a base class (Clause 10) of D. If B is an inaccessible (Clause 11) or ambiguous (10.2) base class of D, a program that necessitates this conversion is ill-formed
Why do I recieve a compile-time error?
main.cpp:17:12: error: cannot cast 'B' to its private base class 'A'
Upvotes: 3
Views: 105
Reputation: 41474
In order for the friend
declaration to make the conversion valid, it needs to take place in a scope where the friendship has effect -- that is, in B
's own code. The fact that A
declares B
as a friend has no effect outside B
's definition.
Upvotes: 4