Why does inheritance affect exception handling?

When searching for the answer to this request with the recording of test code, I found out that private / protected inheritance changes the way of getting exceptions from different classes, which was very surprising. To find the answer, I mentioned the forum questions earlier, and I met this similar question .

It’s quite obvious to me 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 limited to inheritance when virtual method calls are not ? The following snippet explains this:

 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 look at privacy as an answer; received. But why is this only applicable to catch() receiving base pointers, while it is not applicable to functions receiving base pointers?

+7
source share
2 answers

The meaning of private and protected inheritance is that no one in the class or class hierarchy can know about inheritance. This is the same as none of the members of the class can know about a private member.
Having caught the derived class with his base class, he discovered a catcher that the derived class is infact derived from the base class and is a violation of the confidentiality of inheritance.

+10
source

protected Inheritance means only Derived , and its subclasses "know" it also - a Base . main , and the catch statement is not aware of this. This is an access point with specific access.

Virtual dispatch does not care about this - if you have access to a virtual function call, then virtual dispatch is used.

In your example, you cannot use Derived as if it were Base anywhere else in the main scope - so it makes sense that you cannot do this in catch either

+5
source

All Articles