Namespaces
Variants
Views
Actions

typeid operator

From cppreference.com
< cpp‎ | language
Revision as of 08:01, 10 May 2013 by P12 (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

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*