vendredi 20 août 2021

Polymorphism on virtual classes with bad_alloc

I am starting out with c++, out of curiosity I am trying to catch exceptions with polymorphism. I am observing diff behaviours when trying to catch an std exception like bad_alloc vs my custom exception

In case 1 I am throwing a bad_alloc exception which is caught by the catch statement with the argument (exception e) the what statement displays the exception to be bad_alloc().

In case 2 I am throwing MyException which is derived from exception class this is caught by the catch statement with the argument (exception e) the what statement displays the exception to be an "Unknown exception" by which I could figure it was calling the what() function of the base class exception.

In case 3 I am able to call the what() function of child class MyException from the catch while using pointers and "My custom Exception" is getting printed

#include<iostream>
using namespace std;

class MyException : public exception {
public:

    const char* what() const throw() {
        return "My custom Exception";
    }
};
int main() {    

    try {
        bool case1 = false, case2=true, case3=true;
        if (case1) {
            throw bad_alloc(); 
        }
        if (case2) {
            throw MyException();
        }
        if (case3) {
            MyException* o = new MyException();
            throw o;
        }
        
    }   
    catch (exception* e) {
        cout << endl << "catching exception with polymorphism, exception type  is " << e->what();

    }
    catch (exception e) {
        cout << endl << "catching exception with polymorphism  exception type  is " << e.what();

    }

}

My doubt is how is the bad_alloc exception able to call the what() function of itself when there is a rule that Virtual functions(what() in this case) should be accessed using a pointer or reference of base class type to achieve run time polymorphism. Here in this scenario, the virtual function is being accessed by the child class object directly in polymorphism.

Aucun commentaire:

Enregistrer un commentaire