kenics.net

Technical notes on perl, python, php, sql, cgi, c/c++, q/kdb+, unix/shell, revision control tools, data structures & algorithms, and their applications into web services and other various forms of software engineering.

C++ runtime typeid

 
##################### 
###     RTTI     #### 
##################### 
 
RTTI = run time type identification. 
 
in C++, because we have class inheritance, sometimes variable types cannot be determined until the run time. 
 
Let's say a class CChild inherits CParent. 
 
--------------------------- 
CParent cp; 
CChild ch; 
CParent* cpp1 = &cp; 
CParent* cpp2 = &ch; 
 
cpp2->mfunc();               // if virtual function overridden, it will call CChild's mfunc(). if no virtual, it will call CParent's mfunc() 
--------------------------- 
 
if you want/need to know the type of a variable in the above example, you use "typeid" operatior. 
 
----------------------------------------- 
#include <iostream> 
#include <typeinfo>                              //  must include <typeinfo> to use typeid operator 
using namespace std; 
 
class CParent{}; 
class CChild : public CParent {};                // no poly-morphism 
 
class CSuper{ public: virtual void func(){} };   // poly-morphic 
class CSub : public CSuper {}; 
 
 
int main() 

  int x = 123; 
  cout <<  typeid(x).name() << endl;        //  int 
 
  double* y; 
  cout <<  typeid(y).name() << endl;        //  pointer to double 
 
 
  CParent cp; 
  CChild ch; 
  CParent* cpp1 = &cp; 
  CParent* cpp2 = &ch; 
 
  const type_info& ti0 = typeid( *cpp1 );    // typeid operator returns a reference to a const "type_info" 
  const type_info& ti1 = typeid( *cpp2 );    // "type_info" is a class 
  const type_info& ti2 = typeid(  cpp1 ); 
  const type_info& ti3 = typeid(  cpp2 ); 
 
  cout <<  ti0.name() << endl;               //  CParent 
  cout <<  ti1.name() << endl;               //  CParent                this is important to note. 
  cout <<  ti2.name() << endl;               //  Pointer to CParent 
  cout <<  ti3.name() << endl;               //  Pointer to CParent 
 
  cout <<  typeid( *cpp1 ).name() << endl;   // same as above four lines 
  cout <<  typeid( *cpp2 ).name() << endl; 
  cout <<  typeid(  cpp1 ).name() << endl; 
  cout <<  typeid(  cpp2 ).name() << endl; 
 
 
  CSuper super; 
  CSub sub; 
  CSuper* csp1 = &super; 
  CSuper* csp2 = &sub; 
 
  cout << typeid(*csp1).name() << endl;      // CSuper 
  cout << typeid(*csp2).name() << endl;      // CSub               YES! it's recognized as CSub cos of polymophicity 
  cout << typeid(csp1).name() << endl;       // pointer to CSuper 
  cout << typeid(csp2).name() << endl;       // pointer to CSuper 
 
  return 0; 

------------------------------------------ 
 
(ref) 
http://en.cppreference.com/w/cpp/language/typeid 
http://www.geocities.jp/ky_webid/cpp/language/023.html 
 

  1. 2014-05-08 02:09:57 |
  2. Category : cpp
  3. Page View:

Google Ads