Run-time type information

From Seo Wiki - Search Engine Optimization and Programming Languages
Jump to navigationJump to search

In programming, RTTI (Run-Time Type Information, or Run-Time Type Identification) refers to a C++ system that keeps information about an object's data type in memory at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. This is a C++ implementation of a more generic concept called reflection.

In the original C++ design, Stroustrup did not include run-time type information, because he thought this mechanism was frequently misused[1].

RTTI and dynamic_cast

In order for the dynamic_cast<> operation, the typeid operator or exceptions to work in C++, RTTI must be enabled.

With C++ run-time type information, you can perform safe typecasts and manipulate type information at run time.

RTTI is only available for classes which are polymorphic, which means they have at least one virtual method. In practice, this is not a limitation because a class that you intend to use polymorphically should generally have at least a virtual destructor, to allow objects of derived classes to perform proper cleanup.

C++ Example

/* A base class pointer can point to objects of any class which is derived 
 * from it. RTTI is useful to identify which type (derived class) of object is 
 * pointed to by a base class pointer.
 */

#include <iostream>

class abc   // base class
{
public:
  virtual ~abc() { } 
  virtual void hello() 
  {
    std::cout << "in abc";
  }
};

class xyz : public abc
{
  public:
  void hello() 
  {
    std::cout << "in xyz";
  }
};

int main()
{
  abc *abc_pointer = new xyz();
  xyz *xyz_pointer;

  // to find whether abc_pointer is pointing to xyz type of object
  xyz_pointer = dynamic_cast<xyz*>(abc_pointer);

  if (xyz_pointer != NULL)
    std::cout << "abc_pointer is pointing to a xyz class object";   // identified
  else
    std::cout << "abc_pointer is NOT pointing to a xyz class object";

  // needs virtual destructor 
  delete abc_pointer;

  return 0;
}

An instance where RTTI is used is illustrated below:

class base {
  virtual ~base(){}
};

class derived : public base {
  public:
    virtual ~derived(){}
    int compare (derived &ref);
};

int my_comparison_method_for_generic_sort (base &ref1, base &ref2)
{
  derived & d = dynamic_cast<derived &>(ref1); // rtti used here
  // RTTI enables the process to throw a bad_cast exception
  // if the cast is not successful
  return d.compare (dynamic_cast<derived &>(ref2));
}

See also

References

de:Runtime Type Information fr:Run-time type information it:RTTI ja:実行時型情報 pl:RTTI pt:Runtime Type Information ro:Runtime Type Information ru:Динамическая идентификация типа данных zh:執行期型態訊息

If you like SEOmastering Site, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...