+ 1

Can you help me with base class reference to derived classes? Thank you :)

In my below code, I threw an exception of type derived(derived from base), and created two catch blocks, one with base argument and one with derived argument. But when I inherit derived publicly from base, the base catch statement which is defined before derived catch, catches it. When I inherit it default(private), the catch block with derived argument catches it. Why is it happening so?? Any answers are highly appreciated :) https://code.sololearn.com/cGWiz5VzFs9A/?ref=app

17th Aug 2021, 11:39 AM
Rishi
Rishi - avatar
1 Réponse
+ 3
The type of inheritance not only influences the new access modifer of base class members, but also how the inheritance relationship as a whole is known to the outside. If you inherit in a private manner, only the derived class knows it is really derived from the base class, while from the outside, it is not known as a derived class of the base class. For example, in your code, main() does not know "derived" is a child of "base", and therefore the first catch() block is not triggered, as long as the inheritance is private (or protected). See the following thread for a more extensive answer on the differences: https://stackoverflow.com/questions/860339/difference-between-private-public-and-protected-inheritance
17th Aug 2021, 11:53 AM
Shadow
Shadow - avatar