Re: Why does the C++ spec. prohibit downcasting through non-public inheritance?
"Alf P. Steinbach" <alfps@start.no> writes:
* edam:
[...] I cannot understand why a member function of the derived
class or of a friend class can not downcast a protected base class
reference to a derived class reference specifically because we are
using protected inheritance.
Consider a class hierarchy Base and SomeoneElsesDerived with protected
inheritance from Base.
If you could downcast from Base to your own protected class then you
could upcast from SomeoneElsesDerived and down to your own class,
gaining access to Base stuff in that SomeoneElsesDerived object.
'protected' would then not mean anything
In order for this to be understood as an answer to the OP's question, it
would need to be the case that described upcast-plus-downcast would be
okay where protected inheritance was not used. Are you suggesting that
the following would `succeed'?:
struct Base { virtual ~Base() { } };
struct SomeoneElsesDerived : public Base { };
struct MyDerived : public Base { };
int main()
{
SomeoneElsesDerived sed;
Base& b = dynamic_cast<Base&>(sed);
MyDerived& md = dynamic_cast<MyDerived&>(b);
}
As it clearly would not, can you expand on how an example that fails in
all instances can be used as an argument against what the OP expects
should happen in a specific one?
Regards
Paul Bibbings