Namespaces
Variants
Views
Actions

typeid operator

From cppreference.com
< cpp‎ | language
Revision as of 14:49, 4 March 2013 by Cubbi (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
 

Queries information of a type.

Used where the actual type of a virtual base class must be known.

Contents

Syntax

typeid( Template:sparam ) (1)
typeid( Template:sparam ) (2)

Header <typeinfo> must be included before using typeid operator.

Both versions return an object of type const std::type_info&.

Explanation

1) returns the type information about the Template:sparam. The type will be definitely known compile time and no runtime overhead is caused.

2) Template:sparam is evaluated and type information corresponding to the resulting value is returned. If the Template:sparam is (or evaluates to) a polymorphic object, the actual type of the class is queried dynamically with some runtime overhead. Otherwise the actual type is definitely known compile time and no runtime overhead is incurred.

Keywords

typeid

Example

#include <iostream>
#include <string>
#include <typeinfo>
 
int main(void) 
{
    int myint = 50;
    std::string mystr = "string";
    double *mydoubleptr = new double;
 
    *mydoubleptr = 50.5321;
 
    std::cout << "myint has type: " << typeid(myint).name() << '\n';
    std::cout << "mystr has type: " << typeid(mystr).name() << '\n';
    std::cout << "mydoubleptr has type: " << typeid(mydoubleptr).name() << '\n';
 
   delete mydoubleptr;
}

Possible output:

myint has type: int
mystr has type: std::basic_string<char, std::char_traits<char>, std::allocator<char> >
mydoubleptr has type: double*