บทนำ
ในส่วนนี้เราจะดูว่า RTTI (Runtime Type Information) ใน C++ คืออะไร RTTI เป็นกลไกที่เปิดเผยข้อมูลเกี่ยวกับชนิดข้อมูลของออบเจ็กต์ระหว่างรันไทม์ ฟีเจอร์นี้ใช้ได้ก็ต่อเมื่อคลาสมี virtual function อย่างน้อยหนึ่งฟังก์ชัน มันช่วยให้ชนิดของออบเจ็กต์ถูกกำหนดได้ขณะที่โปรแกรมทำงานอยู่
ในตัวอย่างต่อไปนี้ โค้ดแรกจะไม่ทำงาน จะเกิด error "cannot dynamic_cast base_ptr (of type Base*) to type 'class Derived*' (Source type is not polymorphic)" เพราะไม่มี virtual function
ตัวอย่างโค้ดที่ไม่ทำงาน
#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;
}
ตัวอย่างโค้ดที่ทำงาน (เพิ่ม virtual function)
#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