इस सेक्शन में, हम देखेंगे कि C++ में RTTI (रनटाइम टाइप इंफॉर्मेशन) क्या है। C++ में RTTI एक तंत्र है, जो रनटाइम के दौरान किसी ऑब्जेक्ट के डेटाटाइप के बारे में जानकारी उजागर करता है। यह सुविधा केवल तभी उपलब्ध हो सकती है जब क्लास में कम से कम एक वर्चुअल फंक्शन हो। यह प्रोग्राम निष्पादित होने पर ऑब्जेक्ट के प्रकार को निर्धारित करने की अनुमति देता है।
निम्नलिखित उदाहरण में, पहला कोड काम नहीं करेगा। यह "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() { //खाली फंक्शन } }; 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