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

Last Updated : 18 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, RTTI (Run-time type information) is a mechanism that exposes information about an object’s data type at runtime and is available only for the classes which have at least one virtual function. It allows the type of an object to be determined during program execution.

Runtime Casts

The runtime cast, which checks that the cast is valid, is the simplest approach to ascertain the runtime type of an object using a pointer or reference. This is especially beneficial when we need to cast a pointer from a base class to a derived type. When dealing with the inheritance hierarchy of classes, the casting of an object is usually required. There are two types of casting: 

  • Upcasting: When a pointer or a reference of a derived class object is treated as a base class pointer.
  • Downcasting: When a base class pointer or reference is converted to a derived class pointer.

Using ‘dynamic_cast‘: In an inheritance hierarchy, it is used for downcasting a base class pointer to a child class. On successful casting, it returns a pointer of the converted type and, however, it fails if we try to cast an invalid type such as an object pointer that is not of the type of the desired subclass.

For example, dynamic_cast uses RTTI and the following program fails with the error “cannot dynamic_cast `b’ (of type `class B*’) to type `class D*’ (source type is not polymorphic) ” because there is no virtual function in the base class B.

CPP




// C++ program to demonstrate
// Run Time Type Identification(RTTI)
// but without virtual function
 
#include <iostream>
using namespace std;
 
// initialization of base class
class B {};
 
// initialization of derived class
class D : public B {};
 
// Driver Code
int main()
{
    B* b = new D; // Base class pointer
    D* d = dynamic_cast<D*>(b); // Derived class pointer
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar(); // to get the next character
    return 0;
}


 Adding a virtual function to the base class B makes it work.

CPP




// C++ program to demonstrate
// Run Time Type Identification successfully
// With virtual function
 
#include <iostream>
using namespace std;
 
// Initialization of base class
class B {
    virtual void fun() {}
};
 
// Initialization of Derived class
class D : public B {
};
 
// Driver Code
int main()
{
    B* b = new D; // Base class pointer
    D* d = dynamic_cast<D*>(b); // Derived class pointer
    if (d != NULL)
        cout << "works";
    else
        cout << "cannot cast B* to D*";
    getchar();
    return 0;
}


Output

works


Previous Article
Next Article

Similar Reads

Difference Between Compile Time And Run Time Polymorphism In C++
In this article, we will discuss the differences between the compile-time and runtime polymorphism in C++. What is Polymorphism? Poly means many and morph means forms or shape. Thus the word Polymorphism comes from Greek and it basically means having many forms. For example, Your DAD is your father. He's your mom's Husband. He's your grandma's son
4 min read
How to Determine if a Type is an STL Container at Compile Time?
In C++, Standard Template Library (STL) provides many containers such as std::vector, std::list, std::map, and more. What if we want to write a generic code that behaves differently when a given type is an STL container? To do this we need to determine at compile time whether a given type is an STL container or not. In this article, we will learn d
6 min read
VS Code | Compile and Run in C++
In this article, we will learn how to compile and run C++ program in VS Code. There are two ways of doing that you can use any one of them as per your convenience. It is to be noted that a majority of competitive programmers use C++, therefore the compilation and execution of the program needs to be done quickly. Some methods which are discussed in
3 min read
How To Compile And Run a C/C++ Code In Linux
C Programming Language is mainly developed as a system programming language to write kernels or write an operating system. C++ Programming Language is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance. In this article, we will be compiling and executing the C Programming Language codes and also C
3 min read
VS Code | Build, Run and Debug in C++
In this article, we will discuss the VS Code setup required for break-point debugging. Firstly create a file launch.json that configures the VS Code to launch the GDB debugger at the beginning of the debugging process. Then create a file tasks.json that tells VS Code how to build (compile) the program. Finally, make some changes to the console sett
6 min read
Data type of character constants in C and C++
In C, data type of character constants is int, but in C++, data type of same is char. If we save below program as test.c then we get 4 as output (assuming size of integer is 4 bytes) and if we save the same program as test.cpp then we get 1(assuming size of char is 1 byte) C/C++ Code // C++ program demonstrating that data type of character // const
1 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It
2 min read
C++ set for user define data type
The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.). And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the proper
2 min read
C++ map having key as a user define data type
C++ map stores keys in ordered form (Note that it internally use a self balancing binary search tree). Ordering is internally done using operator " < " So if we use our own data type as key, we must overload this operator for our data type. Let us consider a map having key data type as a structure and mapped value as integer. // key's struc
3 min read
reinterpret_cast in C++ | Type Casting operators
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.It does not check if the pointer type and data pointed by the pointer is same or not. Syntax : data_type *var_name = reinterpret_cast <
3 min read
C++ program to find the type of the given iterator
Given a program that uses an iterator, the task is to find the type of iterator used. Examples: Input : vector.begin() Output : Random_Access Iterator Input : list.begin() Output : Bidirectional Iterator There are namely five types of iterators present in the C++ Standard Library which are mentioned below: Forward Iterator in C++ Bidirectional_Iter
2 min read
Template non-type arguments in C++
Prerequisite: Templates in C++ Generally, a C++ template, with a single argument looks like this: template<typename template_name> But it has been seen that a template can have multiple arguments. The syntax for the same would be: template<class T1, class T2, class T3, ........., class Tn> where, n is the number of arguments. It is also
3 min read
C++ Error - Does not name a type
In C++, one of the most common errors that programmers encounter is the “does not name a type” error. The error usually occurs when the programmer writes a piece of code in which the compiler is not able to recognize the type or definition for it. In this article, we are going to explore the “does not name a type” error in C++ in detail, including
6 min read
Strict Type Checking in C++
Strict type checking means the function prototype(function signature) must be known for each function that is called and the called function must match the function prototype. It is done at compile time. The "strictly typed language" refers to a very strongly typed language in which there are more strict restrictions as to how operations can be per
4 min read
C++ Numeric Data Type
There are mainly 3 types of Numeric Data Types in C++ int unsigned intshort intunsigned short int long intunsigned long intlong long intunsigned long long intfloat double long double1. Integer (int) An integer is a type of datatype that can store integer values. Integer acquires 4 bytes in memory and ranges from -2147483648 to 2147483647. Syntax: i
4 min read
char8_t Data Type in C++ 20
The most recent version of the C++ programming language, C++20, was introduced in the year 2020. The char8_t data type is one of the new features added to C++20. This data type was created especially to display UTF-8 encoded characters. Let's understand what char8_t is and how is it different from other character data types. char8_t Data Type In C+
3 min read
Trailing Return Type in C++ 11
The trailing return type syntax, a new method of indicating a function's return type, was introduced in C++11. Before C++11, the return type of a function was typically specified before the function name. However, in some cases, it could be challenging to express complex return types, especially when dealing with template functions or functions wit
2 min read
Type Difference of Character Literals in C and C++
Every literal (constant) in C/C++ will have a type of information associated with it. In both C and C++, numeric literals (e.g. 10) will have int as their type. It means sizeof(10) and sizeof(int) will return the same value.If we compile what we have said in terms of code then it will look something like this.Example: C/C++ Code #include <bits/s
2 min read
Can a C++ class have an object of self type?
A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type. For example, following program works fine. // A class can have a static member of self type #include<iostream> using namespace std; class Test { static Test self; // works fine /* other stuff
2 min read
Catch block and type conversion in C++
Predict the output of following C++ program. C/C++ Code #include <iostream> using namespace std; int main() { try { throw 'x'; } catch(int x) { cout << " Caught int " << x; } catch(...) { cout << "Default catch block"; } } Output: Default catch block In the above program, a character 'x' is thrown and the
2 min read
const_cast in C++ | Type Casting operators
C++ supports following 4 types of casting operators: 1. const_cast 2. static_cast 3. dynamic_cast 4. reinterpret_cast 1. const_cast const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class members inside a const member function. Consider th
4 min read
Conversion of Struct data type to Hex String and vice versa
Most of the log files produced in system are either in binary(0,1) or hex(0x) formats. Sometimes you might need to map this data into readable format. Conversion of this hex information into system defined data types such as 'int/string/float' is comparatively easy. On the other hand when you have some user defined data types such as 'struct' the p
2 min read
Array Type Manipulation in C++
This article demonstrates some of the inbuilt functions that can be used to query and manipulate array types, even a multidimensional array. These functions can be useful in cases we need information or manipulate array we initiated with different dimensions. These functions are defined in header file . Some of the functions include : is_array() :
5 min read
Comparison of boolean data type in C++ and Java
The Boolean data type is one of the primitive data types in both C++ and Java. Although, it may seem to be the easiest of all the data types, as it can have only two values - true or false, but it surely is a tricky one as there are certain differences in its usage in both Java and C++, which if not taken care, can result in an error. The differenc
5 min read
Is there any need of "long" data type in C and C++?
In C and C++, there are four different data type available for holding the integers i.e., short, int, long and long long. Each of these data type requires different amounts of memory. But there is a catch, the size of "long" data type is not fixed unlike other data types. It varies from architectures, operating system and even with compiler that we
4 min read
Function Overloading and Return Type in C++
Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type. Why is Function overloading not possible with different return types and identical parameters? Function
2 min read
Data Type Ranges and their macros in C++
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can be directly assigned to the variable without act
3 min read
Boolean Data Type
In programming languages, we have various data types to store different types of data. Some of the most used data types are integer, string, float, and boolean. The boolean data type is a type of data that stores only two types of values i.e. True or False. These values are not case-sensitive depending upon programming languages. The name Boolean c
13 min read
C++ Type Modifiers
Modifiers are used in C++ to change or give extra meaning to already existing data types. It's added to primitive data types as a prefix to change their meaning. A modifier is used to change the meaning of a basic type so that it better matches the requirements of different circumstances. Following are the C++ data type modifiers: signedunsignedsho
6 min read
Error: std::endl is of Unknown Type when Overloading Operator <<
In C++, the << operator is commonly overloaded for custom output for user-defined types using streams. However, an issue may arise when using std::endl with an overloaded operator<<. It is shown as the type of std::endl being unknown, leading to compilation errors. In this article, we will learn the cause of this issue and how can we re
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg