Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to base class and private inheritance

Tags:

c++

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*?

like image 748
Ronald McBean Avatar asked Sep 05 '11 11:09

Ronald McBean


4 Answers

Private inheritance means that for everyone except B (and B's friends), B is not derived from A.

like image 122
Jan Avatar answered Nov 16 '22 19:11

Jan


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?

like image 35
Donglei Avatar answered Nov 04 '22 12:11

Donglei


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.

like image 8
David Rodríguez - dribeas Avatar answered Nov 16 '22 18:11

David Rodríguez - dribeas


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.

like image 3
Armen Tsirunyan Avatar answered Nov 16 '22 19:11

Armen Tsirunyan