RTTI (Run-time Type Information) trong C++ là cơ chế tiết lộ thông tin kiểu dữ liệu của đối tượng tại runtime. Yêu cầu lớp có ít nhất một hàm ảo (virtual function). Cho phép xác định kiểu đối tượng khi chương trình chạy.
Ví dụ đầu tiên không có hàm ảo -> lỗi dynamic_cast. Thêm hàm ảo thì hoạt động.
Ví dụ không có hàm ảo (lỗi)
#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;
}
Ví dụ có hàm ảo (hoạt động)
#include <iostream>
using namespace std;
class Base {
virtual void 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;
}
Kết quả
It is working