Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Inheritance influences Exception handling?

While finding answer for this query with writing test code, I got to know that private/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 ?

like image 341
iammilind Avatar asked Apr 09 '11 08:04

iammilind


2 Answers

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.

like image 129
shoosh Avatar answered Nov 11 '22 23:11

shoosh


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

like image 35
Erik Avatar answered Nov 11 '22 23:11

Erik