While finding answer for this query with writing test code, I got to know that p开发者_JAVA百科rivate/protected inheritance changes the way exceptions are received from various classes, which was very surprising. To find the answer I referred earlier forum questions and I came across this similar question.
For me it's quite obvious to use protected
inheritance for a base class with virtual
methods. Keeping the standard aside, I wanted to know why in C++ exception handling is restricted by inheritance when virtual method calls are Not ?
Following snippet explains it:
struct Base { virtual void printError () = 0; };
class Derived : protected Base { void printError () { } };
int main ()
{
try {
throw new Derived;
}
catch(Base *p) { p->printError(); } // Ideal; but not invoked
catch(void *p) { ((Base*)p)->printError(); } // Ugly; but only way to invoke
}
Edit:
If we consider the privacy regard as an answer; accepted. But then why it's applicable only for catch()
receiving base pointers, while it's not applicable for functions receiving base pointers ?
The meaning of private
and protected
inheritance is that no one outside of the class or class hierarchy can know about the inheritance. This is the same way as no one outside the class can know about a private member.
Catching a derived class by its base class revealed to the catcher that the derived class is infact derived from the base class and is a breach of the privacy of the inheritance.
protected
inheritance means only Derived
and its subclasses "knows" it also is-a Base
. main
, and the catch statement, doesn't "know" this. This is the point of inheriting with a specific access.
Virtual dispatch doesn't care about this - if you have access to call a virtual function, then virtual dispatch is used.
In your sample, you cannot use a Derived
as if it was a Base
anywhere else in the scope of main
- so it makes sense that you can't do it in the catch
either
精彩评论