In C++, why does typeid(*entity).name() print something like 6Player, and how should code compare or key on dynamic types?
answer
- name() is implementation-defined
- mangled on Itanium-ABI toolchains
- compare type_info, not strings
- std::type_index for map keys
- typeid(ptr) versus typeid(*ptr)
basics
~10 sstd::type_info::name() returns an implementation-defined string; GCC and Clang return the mangled name, so Player prints as 6Player. Compare types with type_info's operator== and key containers with std::type_index, never with name() strings.
solid answer
~40 s`typeid(*entity)` yields a `const std::type_info&` for the dynamic type of a polymorphic object. Its `name()` returns an **implementation-defined** string: GCC and Clang return the Itanium-ABI mangled name, `6Player` for `Player`, which `abi::__cxa_demangle` from `<cxxabi.h>` turns back into `Player` on those toolchains. So `name()` is for human-facing logs only. To test a type, compare with `operator==`: `typeid(*entity) == typeid(Player)`, which is an exact-type check, false for subclasses. To use types as keys, wrap them in `std::type_index` (from `<typeindex>`), which is copyable, ordered and hashable; `std::type_info` itself cannot be copied. Watch three traps: `typeid(ptr)` describes the pointer type, not the object; cv-qualifiers and references are dropped; and `typeid(*p)` with a null `p` throws `std::bad_typeid`.
code
cpp · 31 lines#include <iostream>
#include <map>
#include <string>
#include <typeindex>
#include <typeinfo>
struct Entity { virtual ~Entity() = default; };
struct Player : Entity {};
struct Monster : Entity {};
int main() {
Player hero;
const Entity& e = hero;
Entity* ptr = &hero;
std::cout << typeid(e).name() << '\n'; // dynamic type, name is implementation-defined
std::cout << typeid(ptr).name() << '\n'; // a pointer is not polymorphic: static type Entity*
std::cout << (typeid(e) == typeid(Player)) << '\n';
std::cout << (typeid(const Player&) == typeid(Player)) << '\n'; // cv and reference dropped
std::map<std::type_index, std::string> label{
{typeid(Player), "player"}, {typeid(Monster), "monster"}};
std::cout << label[typeid(*ptr)] << '\n';
Entity* gone = nullptr;
try {
std::cout << typeid(*gone).name() << '\n';
} catch (const std::bad_typeid& ex) {
std::cout << "bad_typeid: " << ex.what() << '\n';
}
}go deeper
Know that typeid returns a type_info whose name() is implementation-defined, often mangled, and that types are compared with ==.
Explain dynamic versus static results, type_index for containers, exact-type versus is-a, and the typeid(ptr) mistake.
Keep names out of persistent formats, demangle only for logs, and know why RTTI identity is not just a pointer compare on every platform.
Decide whether a system's type identity should rest on RTTI at all, or on explicit, stable identifiers the team controls.
## What `typeid` gives you `typeid` is an operator that returns an lvalue of type `const std::type_info`, an object describing a type. When its operand is a glvalue of a **polymorphic** class type, such as `*entity` with a virtual destructor in `Entity`, the result describes the **dynamic** type, the type of the complete object. The returned object lives until the end of the program, so holding a reference or pointer to it is safe. `std::type_info` offers few operations: | Member | What the standard promises | |---|---| | `operator==` | true if both describe the same type | | `before` | an implementation's collation order, for sorting | | `hash_code` | equal for equal types within one execution | | `name` | an implementation-defined null-terminated string | It has a deleted copy constructor and copy assignment, so you cannot store a `std::type_info` by value. ## Why the name looks like `6Player` The standard leaves the content of `name()` to the implementation. GCC and Clang, which follow the Itanium C++ ABI on most platforms, return the **mangled** type name: `6Player` (length-prefixed), `P6Entity` for `Entity*`. Other implementations return other strings. The code example, built with Clang, prints `6Player` for the object and `P6Entity` for the pointer. For logs, demangle on those toolchains with `abi::__cxa_demangle` from `<cxxabi.h>`, which returns a `malloc`-allocated string such as `Player` that the caller frees. It is a toolchain facility, not standard C++. What not to do with `name()`: - Do not compare names to test types; use `operator==`. - Do not persist names in save files or network messages; another compiler or version may produce a different string. - Do not parse names to recover namespaces or template arguments; the format is not specified and differs between toolchains. ## Comparing and keying on types `typeid(*e) == typeid(Player)` is an **exact-type** test: true for a `Player`, false for a `Boss` derived from `Player`. That is sometimes exactly what you want, for example when counting objects per concrete class, and sometimes a bug, when the code really meant "is a `Player`", which is what `dynamic_cast` answers. For maps and sets, use `std::type_index` from `<typeindex>`: a copyable wrapper around a `type_info` pointer with comparison operators and a `std::hash` specialization. ```cpp std::map<std::type_index, std::string> label{ {typeid(Player), "player"}, {typeid(Monster), "monster"}}; label[typeid(*ptr)]; // dynamic type of the object ``` Do not key on the address of the `type_info` object or on `hash_code()` alone. The standard defines type identity through `operator==`, not through object identity, and libc++ documents configurations where the linker may leave several copies of a type's RTTI in one program; it then compares names as a fallback. `hash_code()` may collide and is only stable within a single execution. ## How `std::type_index` orders types `std::type_index` stores a pointer to the `type_info`, which is why it can be copied while `type_info` cannot. Its `operator==` compares the referenced `type_info` objects with `==`, and its `operator<` returns `target->before(*rhs.target)`, the implementation's collation order. That order is consistent within one run, which is all a `std::map` needs, but it is not alphabetical and not stable across builds, so never print or persist it. For unordered containers, `std::hash<std::type_index>` uses `hash_code()`, with equality settling collisions, which is why hashing by type index is safe even though `hash_code()` alone is not an identity. ## Three traps in one line of code 1. **Pointer versus object.** `typeid(ptr)` where `ptr` is an `Entity*` describes the type `Entity*`; a pointer is not a polymorphic class glvalue. You almost always meant `typeid(*ptr)`. 2. **cv and references are dropped.** `typeid(const Player&) == typeid(Player)` is true; `typeid` never distinguishes `const` objects or reference types. 3. **Null objects.** `typeid(*p)` where `p` is a null pointer to a polymorphic type throws `std::bad_typeid`, a defined outcome unlike most null dereferences. The code example catches it. ## Construction and destruction Inside a constructor or destructor of `Entity`, the dynamic type of `*this` is `Entity`, not the derived class being built. A `typeid(*this)` there reports `Entity`. Logging the type from a base constructor is therefore misleading. ## What interviewers check - That `name()` is implementation-defined and not a stable identifier. - That equality and `std::type_index` are the right tools, and that `typeid ==` is exact-type, not is-a. - That the candidate spots `typeid(ptr)` versus `typeid(*ptr)`.
- How do you print a readable type name from typeid on GCC or Clang?Pass `typeid(x).name()` to `abi::__cxa_demangle` from `<cxxabi.h>`, with null buffer and length arguments and an `int` for the status. On success, status is 0 and the function returns a `malloc`-allocated string such as `Player`, which the caller must `free`. It is part of the Itanium ABI runtime that GCC and Clang provide, not standard C++, so guard it for other toolchains.
- In C++, what does typeid(*this) report inside Entity's constructor while a Player is being built?It reports `Entity`. During construction and destruction of the `Entity` base, the object behaves as an `Entity`: virtual calls, `typeid` and `dynamic_cast` all treat the class under construction as the dynamic type. A `dynamic_cast<Player*>(this)` there returns null. The object becomes a `Player` only when `Player`'s constructor starts running.
- type_info::name() returns the class name exactly as written in the source.
- Comparing name() strings is the portable way to test two types.
- typeid(ptr) on an Entity* reports the type of the pointed-to object.
- typeid(*e) == typeid(Player) is also true for classes derived from Player.
- Each type has exactly one type_info object, so comparing addresses is enough.