zoukankan      html  css  js  c++  java
  • RTTI (Run-time type information) in C++

      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

  • 相关阅读:
    LinkedList的使用方法
    规范HTML页面
    HTML总结(一)
    HTML标签学习总结
    java---线程池的使用
    java对excel表格的操作
    java对cookie及Session的操作
    硬盘分区工具gparted使用
    镜像, 转置, 锐化, 灰度,旋转
    ffmpeg解码
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3444149.html
Copyright © 2011-2022 走看看