Open In App

How to Find the Type of an Object in C++?

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, every variable and object has a type. The type of an object determines the set of values it can have and what operations can be performed on it. It’s often useful to be able to determine the type of an object at runtime, especially when dealing with complex codebases. In this article, we will learn how to find the type of an object in C++.

Example:

Input:
int myInt = 10;
double myDouble = 20.0;

Output:
The type of myInt is: i (int)
The Type of myDouble is: d (double)

Find the Type of an Object in C++

To find the type of an object in C++, we can use the typeid operator provided by the type_info library. The typeid operator returns a reference to a type_info object, which can then be used to get the name of the type. Following is the syntax to use the typeid operator in C++:

Syntax of typeid

typeid(object_name).name()

where:

  • object_name: is the name of the object whose type we want to determine.
  • name(): The name() method is used to obtain a human-readable representation of the object type.
  • return type: const std::type_info object representing the type of the expression.

C++ Program to Find the Type of an Object

The below example demonstrates the use of the typeid operator to find the type of a given object in C++.

C++
// C++ program to find the type of an object

#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{
    // Declare an int and a double
    int myInt = 10;
    double myDouble = 20.0;

    // Use typeid to find the type of myInt
    cout << "Type of myInt is : " << typeid(myInt).name()<< endl;

    // Use typeid to find the type of myDouble
    cout << "Type of myDouble is : "<< typeid(myDouble).name() << endl;

    return 0;
}

Output
Type of myInt is : i
Type of myDouble is : d

Time Complexity: O(1)
Auxiliary Space: O(1)

Note: Here i denotes the object is of type int and d denotes the object is of type double.


Next Article
Practice Tags :

Similar Reads