다형성을 적용하지 않는 경우
#include <iostream>
using namespace std;
class Exception
{
public:
void report()
{
cerr << "Exception report\n";
}
};
class ArrayException : public Exception
{
public:
void report()
{
cerr << "Array exception report\n";
}
};
class MyArray
{
int data_[5];
public:
int& operator[] (const int& index)
{
if (index < 0 || index >= 5)
throw ArrayException();
return data_[index];
}
};
void doSomething()
{
MyArray my_array;
try
{
my_array[100];
}
catch (Exception& e)
{
e.report();
}
}
int main()
{
doSomething();
}
/* stdout stderr
Exception report
*/
- 객체 잘림으로 인해
Exception::report()
함수가 작동한 것을 알 수 있다.
다형성을 적용한 경우 (virtual
키워드 사용)
#include <iostream>
using namespace std;
class Exception
{
public:
virtual void report()
{
cerr << "Exception report\n";
}
};
class ArrayException : public Exception
{
public:
void report()
{
cerr << "Array exception report\n";
}
};
class MyArray
{
int data_[5];
public:
int& operator[] (const int& index)
{
if (index < 0 || index >= 5)
throw ArrayException();
return data_[index];
}
};
void doSomething()
{
MyArray my_array;
try
{
my_array[100];
}
catch (Exception& e)
{
e.report();
}
}
int main()
{
doSomething();
}
/* stdout stderr
Array exception report
*/
맨 처음 catch
된 부분만 처리된다.
#include <iostream>
using namespace std;
class Exception
{
public:
void report()
{
cerr << "Exception report\n";
}
};
class ArrayException : public Exception
{
public:
void report()
{
cerr << "Array exception report\n";
}
};
class MyArray
{
int data_[5];
public:
int& operator[] (const int& index)
{
if (index < 0 || index >= 5)
throw ArrayException();
return data_[index];
}
};
void doSomething()
{
MyArray my_array;
try
{
my_array[100];
}
catch (Exception& e)
{
e.report();
}
catch (ArrayException& e)
{
e.report();
}
}
int main()
{
doSomething();
}
/* stdout stderr
Exception report
*/
warning C4286: 'ArrayException &': is caught by base class ('Exception &') on line 44
따로 처리해야 하는 경우에는 더 작은 범위의 클래스를 위에 두면 된다.
#include <iostream>
using namespace std;
class Exception
{
public:
void report()
{
cerr << "Exception report\n";
}
};
class ArrayException : public Exception
{
public:
void report()
{
cerr << "Array exception report\n";
}
};
class MyArray
{
int data_[5];
public:
int& operator[] (const int& index)
{
if (index < 0 || index >= 5)
throw ArrayException();
return data_[index];
}
};
void doSomething()
{
MyArray my_array;
try
{
my_array[100];
}
catch (ArrayException& e)
{
e.report();
}
catch (Exception& e)
{
e.report();
}
}
int main()
{
doSomething();
}
/* stdout stderr
Array exception report
*/