인프런 커뮤니티 질문&답변
[05:17] 상속을 사용할 때 주의가 필요한 경우(객체잘림)
해결된 질문
작성
·
258
1
안녕하세요?
05분17초에 상속을 사용할 때 주의가 필요한 경우를 설명해주시고 계신대요.
이 부분에서 갑자기 virtual 키워드가 떠올라서
Base class에 virtual을 붙여줬더니
class Exception
{
public:
virtual void report()
{
cerr << "Exception report" << endl;
}
};
class ArrayException : public Exception
{
public:
void report()
{
cerr << "Array exception" << endl;
}
};
// catch (ArrayException & e)
// {
// e.report();
// }
catch (Exception & e)
{
e.report();
}
받아주는 쪽에서 ArrayException을 받는 부분을 추가를 안해줘도 (주석 부분)
Derived class(ArrayException)의 report가 실행이 되더라고요.
이 부분이 이렇게도 가능한건가요?
만약 가능하다고 해도 사용안하는 게 좋은 거라면 그 이유는
12-2에서 virtual 키워드 설명해주실 때
virtual 키워드는 호출이 아주 빈번하게 되는 함수에는 쓰면 안좋다고 설명해주셨는데
try catch 예외처리는 문제가 생길 수 있는 부분에 대해 처리하는 부분인 만큼 자주 실행될 수 있는 부분이니까
virtual 키워드를 사용 안하는 게 좋은 건가요?
감사합니다.
<code>
// 14_3.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
class Exception
{
public:
virtual void report()
{
cerr << "Exception report" << endl;
}
};
class ArrayException : public Exception
{
public:
void report()
{
cerr << "Array exception" << endl;
}
};
class MyArray
{
private:
int m_data[5];
public:
int& operator [] (const int& index)
{
//if (index < 0 || index >= 5) throw - 1;
if (index < 0 || index >= 5) throw ArrayException();
return m_data[index];
}
};
void doSomething()
{
MyArray my_array;
try
{
my_array[100];
}
catch (const int& x)
{
cerr << "Exception " << x << endl;
}
// catch (ArrayException & e)
// {
// e.report();
// }
catch (Exception & e)
{
e.report();
}
}
int main()
{
doSomething();
// try
// {
// doSomething();
// }
// catch (Exception & e)
// {
// cout << "main()" << endl;
// e.report();
// }
// catch (ArrayException & e)
// {
// cout << "main()" << endl;
// e.report();
// }
return 0;
}





