RTTI is the abbreviation for "Runtime type information", meaning: Run-time type information. It provides a way to determine the type of object at run time. This article will briefly describe some of RTTI's background knowledge, describe the concept of RTTI, and explain when and how to use RTTI with specific examples and code, and this article will detail the use of two important RTTI operators, typeID and dynamic_cast.
In fact, RTTI is not a new thing in C + +, it has appeared as early as more than 10 years ago. But most developers, including many high-level C + + programmers, are not familiar with it, let alone using RTTI to design and write applications.
Some object-oriented experts in the dissemination of their own design concepts, most of the advocate in the design and development of the use of virtual member functions, rather than RTTI mechanism. However, in many cases, virtual functions cannot overcome their limitations. When it comes to dealing with heterogeneous containers and basic class hierarchies (such as MFC), it is inevitable to dynamically judge the type of object, that is, the dynamic type of detection. How do you determine the dynamic type of an object? The answer is to use the operators in the built-in RTTI: typeID and dynamic_cast.
Let's first design a class hierarchy, assuming we create an abstract base class for a processing file. It declares the following pure virtual functions: open (), close (), read (), and write ():class File
{
public:
virtual int open(const string & filename)=0;
virtual int close(const string & filename)=0;
//
virtual ~File()=0; // 记住添加纯虚拟析构函数(dtor)
};
Classes that derive from the File class now implement the pure virtual functions of the base class, while providing some additional operations. Assuming that the derived class is diskfile, you implement your own flush () and defragment () operations in addition to the pure virtual functions of the base class:class DiskFile: public File
{
public:
int open(const string & filename);
// 实现其他的纯虚拟函数
......
// 自己的专有操作
virtual int flush();
virtual int defragment();
};
It then derives two classes from the Diskfile class, assuming Textfile and MediaFile. The former is for text files, and the latter for audio and video files:class TextFile: public DiskFile
{
// ......
int sort_by_words();
};
class MediaFile: public DiskFile
{
//......
};
The reason we want to create this class hierarchy is because we can create polymorphic objects later, such as:
File *pfile; // *pfile的静态类型是 File
if(some_condition)
pfile = new TextFile; // 动态类型是 TextFile
else
pfile = new DiskFile; // 动态类型是 DiskFile