×

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function. It enables the type of an object to be determined while the application is running.

Let's say a class descends from a base class that includes virtual functions. In that situation, the C++ language mandates that a pointer to the base class type can call the virtual function implementations in the derived class object. Occasionally, a class containing virtual functions is referred to as a "polymorphic class."

Durational Casts

The simplest method to determine the runtime type of an item that used a pointer or reference is the runtime cast, which verifies that the cast is legal. This is useful when we need to cast a reference from a class name to a derived type. Casting an object is frequently required when working with the class inheritance structure.

Casting might be of two different kinds:

  • Upcasting: It is when a pointer or reference to a derived class object is considered a base class pointer.
  • Downcasting: The conversion of a reference or pointer to a derived class from a pointer to a base class.

To downcast a base class pointer to a child class in an inheritance tree, utilize "dynamic cast." Unless we attempt to cast an incorrect type, such as an object reference that is not of the kind of the intended subclass, casting correctly produces a pointer of a converted type.

Runtime data types for objects are only available to classes with at least one virtual function. During program execution, it enables the type of an object to be determined.

Because base class B is missing a virtual function, the following program encounters the error "cannot dynamic convert 'b' (of type 'class B*' to type 'category D*' (classifier is not polymorphic)." This is because dynamic cast requires RTTI. See the following C++ program.

Example:

// Run Time Type Identification (RTTI)
// however, lacking a virtual function
#include <iostream>
usingnamespace std;
 
// however, lacking a virtual function
class B {};
 
// setting up a derived class
class D : public B {};
 
// Driver Number
int main()
{
    B* b = new D; // pointer to base class
    D* d = dynamic_cast<D*>(b); // class pointer derived
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar(); // for the subsequent character
    return 0;
}

It works by giving the base class B a virtual function.

// a C++ application to show
// Successful Run Time Type Identification
// virtual capability
 
#include <iostream>
usingnamespace std;
 
// setting up the base class
class B {
    virtualvoid fun() {}
};
 
// the beginning of a derived class 
class D: public B {
};
 
// Driver Number
int main()
{
    B* b = new D; // pointer to base class
    D* d = dynamic_cast<D*>(b); // class pointer derived
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}

Output:

RTTI (Run-Time Type Information) in C++

RTTI abuses

In C++ projects, RTTI should only be applied sparingly. This is due to several factors. Most notably, RTTI is rarely better than other language techniques like polymorphism and templates. Although there are always exceptions, the general norm for RTTI is like that for go-to statements. Refrain from utilizing it to avoid using a good, more reliable design. Apply RTTI only when it makes sense, and you are confident in using it.

Limitations

The RTTI has various restrictions. First, only polymorphic types can be utilized with RTTI. This means that either directly or indirectly through inheritance, each of your classes must contain at least one virtual function. Second, certain compilers need a special option to enable RTTI because of the extra data needed to store types.

Be aware that under RTTI, references to pointers will not function:

void example( int*& reforest )
{
        std::cout << "What type is *&refptrTest : " <<typeid( refptrTest ).name() << std::endl;
}

As typeid() does not accept reference types, it will report int*.

Note: Before using operator typeid within a compilation unit, the header file <type info> must be included according to the C++98 standard. The software is deemed incomplete if not.


Related Topics

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

Handling multiple clients on the Server with multithreading using Socket Programming in C or C++

To understand this guide completely, the reader is assumed to be familiar with the foundations of server and client models and socket programming. If one wants to create any scalable...

7 minutes read.