ในส่วนนี้เราจะมาดูกันว่าอะไรคือ RTTI (ข้อมูลประเภทรันไทม์) ใน C++ ใน C ++ RTTI เป็นกลไกที่แสดงข้อมูลเกี่ยวกับประเภทข้อมูลของอ็อบเจ็กต์ระหว่างรันไทม์ คุณลักษณะนี้จะใช้ได้เฉพาะเมื่อคลาสมีฟังก์ชันเสมือนอย่างน้อยหนึ่งฟังก์ชัน อนุญาตให้กำหนดประเภทของวัตถุเมื่อโปรแกรมกำลังทำงาน
ในตัวอย่างต่อไปนี้ รหัสแรกจะไม่ทำงาน มันจะสร้างข้อผิดพลาดเช่น "cannot dynamic_cast base_ptr (ประเภท Base*) เพื่อพิมพ์ 'class Derived*' (ประเภทแหล่งที่มาไม่ใช่ 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