The following simple example will produce a compiler error, since I accidently use private inheritance:
main.cpp:21: error: ‘A’ is an inaccessible base of ‘B’
class A
{
};
class B : /*ups forgot that -> public*/ A
{
};
int main(int , char *[])
{
A* test = new B;
return 0;
}
Could you help me and explain what exactly is inaccessible in the base class and why it is needed in the conversion from B*
to A*
?
Private inheritance means that for everyone except B (and B's friends), B is not derived from A.
Since the reference or pointer of Base class can not point to object of inherited class, does it mean that protected and private inheritance is nothing to do with polymorphism?
Could you help me and explain what exactly is inaccessible in the base class and why it is needed in the conversion from B* to A*?
Ouside of B
and the friends of B
, the simple fact that B
is an A
is not visible. This is not hiding a member variable or member function, but hiding the relationship itself. That is why from main
you cannot bind the result of new B
with a pointer to A
, because as far as main
is concerned, B
is not an A
(in the same way that you could not do A * p = new unrelated;
)
As to why it is needed, the answer it exactly the same: because without access to the relationship, the compiler does not know (well, it knows, but will not tell you) how to obtain a pointer to the A
subject inside B
, because as far as it can see within that context there is no relationship between A
and B
at all.
The conversion from B*
to A*
is inaccessible, because the base-class subobject is private. When you convert B*
to A*
, you return the pointer to the base-class subobject. The latter must be accessible for the conversion to be accessible. In any function that is friend to B
the conversion becomes accessible. By the way, you can always access the conversion by an explicit cast.
A* p = (A*)(new B);
Note that in some cases just accessible conversion is required, but in some cases it is required that A
be a public (stronger than accessible) base of B
. For example, when you try to catch an exception of type B
with catch(A&)
- it is required that A
be a public base class of B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With