In accessible base class for return pointer type

S

Steven T. Hatton

Can somebody explain why making T a friend of either B or C will permit the
code to compile?

class A{ protected: A(){} };
class T;
class B: protected A {protected: B(){}/*friend class T;*/};
class C: public B {public : C(){}/*friend class T;*/};
struct T { A* newA() {return new C();}};
int main() {}

This is the error I get if I do not use one of the friend declarations:
In member function ?A* T::newA()?: error: ?A? is an inaccessible base of ?C?
 
V

Victor Bazarov

Steven said:
Can somebody explain why making T a friend of either B or C will
permit the code to compile?

class A{ protected: A(){} };
class T;
class B: protected A {protected: B(){}/*friend class T;*/};
class C: public B {public : C(){}/*friend class T;*/};
struct T { A* newA() {return new C();}};
int main() {}

This is the error I get if I do not use one of the friend
declarations:
In member function ?A* T::newA()?: error: ?A? is an inaccessible base
of ?C?

Conversions from a pointer to derived to a pointer base require the
base to be accessible. If 'A' is a protected base of 'C' (through
'B'), then no outside class/function can convert a pointer to 'C' to
a pointer to 'A'. Since 'B' is a public base of 'C', anyone can
convert a 'C*' to a 'B*'.

What book on C++ are you reading that doesn't explain access specifiers
and their effect?


V
 
S

Steven T. Hatton

Victor said:
Conversions from a pointer to derived to a pointer base require the
base to be accessible. If 'A' is a protected base of 'C' (through
'B'), then no outside class/function can convert a pointer to 'C' to
a pointer to 'A'. Since 'B' is a public base of 'C', anyone can
convert a 'C*' to a 'B*'.

What book on C++ are you reading that doesn't explain access specifiers
and their effect?


V

I guess I could/should have looked it up. I just wanted to see what others
had to say about it. After your suggestion that I access a reference, I
did take a look at TC++PL(SE) §15.3.2. Basically what it says, and what
you said are the supposition I drew from the example. Part of what was
unclear in my mind is what scope the conversion takes place in. The
original code was calling the counterpart of C::newA (above) from within
the counterpart of A. It took some time to untangle what was happening
because I had never encountered that particular situation, that I can
remember.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top