In C++, RTTI (Run-time type information) is available only for the classes which have at least one virtual function.
For example, dynamic_cast uses RTTI and following program fails with error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.
1 #include<iostream> 2 3 using namespace std; 4 5 class B 6 { 7 }; 8 class D: public B 9 { 10 }; 11 12 int main() 13 { 14 B *b = new D; 15 D *d = dynamic_cast<D*>(b); 16 if(d != NULL) 17 { 18 cout<<"works"; 19 } 20 else 21 { 22 cout<<"cannot cast B* to D*"; 23 } 24 getchar(); 25 return 0; 26 }
Adding a virtual function to the base class B makes it working.
1 #include<iostream> 2 3 using namespace std; 4 5 class B 6 { 7 public: 8 virtual void fun() 9 { 10 } 11 }; 12 class D: public B 13 { 14 }; 15 16 int main() 17 { 18 B *b = new D; 19 D *d = dynamic_cast<D*>(b); 20 if(d != NULL) 21 { 22 cout<<"works"; 23 } 24 else 25 { 26 cout<<"cannot cast B* to D*"; 27 } 28 getchar(); 29 return 0; 30 }
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 21:13:16