×

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

How to Reverse a String in C++ using 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 condition no longer...

6 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.

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.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 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++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Type conversion in C++

Type conversion is the process of changing the type of variables in a program. The ultimate goal of type conversions is to allow variables of a single data type operate with...

7 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.