이 섹션에서는 C++의 RTTI(런타임 유형 정보)가 무엇인지 알아봅니다. C++에서 RTTI는 런타임 동안 개체의 데이터 유형에 대한 정보를 노출하는 메커니즘입니다. 이 기능은 클래스에 하나 이상의 가상 기능이 있는 경우에만 사용할 수 있습니다. 프로그램이 실행될 때 개체의 유형을 결정할 수 있습니다.
다음 예에서는 첫 번째 코드가 작동하지 않습니다. "cannot dynamic_cast base_ptr(Type Base*) to type 'class Derived*'(소스 유형이 다형성이 아님)"와 같은 오류가 생성됩니다. 이 오류는 이 예제에 가상 함수가 없기 때문에 발생합니다.
예시 코드
#include<iostream>
using namespace std;
class Base { };
class Derived: public Base {};
int main() {
Base *base_ptr = new Derived;
Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
if(derived_ptr != NULL)
cout<<"It is working";
else
cout<<"cannot cast Base* to Derived*";
return 0;
} 이제 가상 메서드를 추가하면 작동합니다.
예시 코드
#include<iostream>
using namespace std;
class Base {
virtual void function() {
//empty function
}
};
class Derived: public Base {};
int main() {
Base *base_ptr = new Derived;
Derived *derived_ptr = dynamic_cast<Derived*>(base_ptr);
if(derived_ptr != NULL)
cout<<"It is working";
else
cout<<"cannot cast Base* to Derived*";
return 0;
} 출력
It is working