인프런 커뮤니티 질문&답변
9:40 throw custom exception
작성
·
230
2
바로 이전강의에서 클래스를 throw시 , catch를 부모클래스로 하면 객체잘림이 발생하여 , 자식클래스의 오버라이딩된 함수가 구현되지 않고 부모의 함수가 구현되는 모습을 볼 수 있었습니다.
그런데 여기서는 throw Custom exception을 하고 아래에서 catch(std::exception &exception) 즉 부모클래스로 받는데도 exception.what()을 하면 자식클래스인 Custom exception.what()이 실행되는 모습을 볼 수있습니다.
왜그런가요?
답변 2
6
std::exception의 what 의 선언에는 virtual 이 붙어있기 때문입니다.
(https://en.cppreference.com/w/cpp/error/exception/what 참고)
이 경우에 child class를 parent class의 pointer 나 reference에 넣더라도 virtual table이 바뀌지 않기 때문에 (https://www.learncpp.com/cpp-tutorial/125-the-virtual-table/ 혹은 강의 12.6 참고)
child class의 what이 실행됩니다.
1





