Topic: sibling dynamic casts and friend
Author: b91926@fnclub.fnal.gov (David Sachs)
Date: 31 May 1994 20:55:57 GMT Raw View
What are the accessibility rules for using dynamic_cast to access a sibling class? The information I have found about dynamic_cast is articles in C++ Report, and in Bjarne Stroustrup's latest book do not cover this point.
The test program at the end of this message, which I tried with Borland C++ 4.0, shows that BCC 4.0 does NOT allow a dynamic_cast to the private bnase of a derived class, even when the dynamic_cast is performed from a friend function.
I would consider allowing only global (public) accessibility in cases like this, but this should explicitly be in the standard. I doubt that the standards committee would wish to require run-time accessability determination.
***** Test Program follows *****
#include <iostream.h>
#include <typeinfo.h>
class Base1
{
virtual void f() {}
};
class Base2
{
virtual void f() {}
};
class Derived : public Base1, Base2
{
friend Base2* b12(Base1* pb);
};
Base2* b12(Base1* pb)
{
return dynamic_cast<Base2 *>(pb);
}
int main()
{
try
{
Derived d, *pd;
Base1 *b1 = &d;
Base2 *b2;
if (b2 = b12(b1))
{
cout << "Pointer points to type: " << typeid(*b2).name() << endl;
}
else throw Bad_cast();
}
catch(Bad_cast)
{
cout << "Dyamic cast failed" << endl;
return 1;
}
catch(...)
{
cout << "Exception handling error" << endl;
return 2;
}
return 0;
}