C++: Throwing a derived class by reference does not work when catching base class

前端 未结 4 952
小鲜肉
小鲜肉 2020-12-16 17:38

I want to throw my own exceptions with the base class Exception. There is a virtual method print which will be overwritten by the subclasses. I onl

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 18:15

    You can use a pointer instead of reference to avoid slicing:

    int main(int argc, char **argv)
    {
        try
        {
            IllegalArgumentException* pIAE = new IllegalArgumentException();
            throw pIAE;
        }
        catch(IllegalArgumentException* i)
            {
                i->print();
        }
    }
    

    The caught pointer points to the same object, because the copy constructor is not called implicitly.

提交回复
热议问题