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