Sometimes we need to determine the variable type at runtime in C++ code. This tutorial will discuss how to get the type of a variable in C++.
The typeid operator allows us to determine the type of variable/object at runtime.
The syntax of typeid operator
typeid ( type )
typeid ( expression )
Parameters:
Typeid operator accepts one parameter :
- Type – Variable or object.
- Expression – Any valid expression.
Returns:
The typeid operator returns an lvalue of type const std::type_info that represents the type of expression.
To use the typeid operator we must include the STL header<typeinfo>.
Examples
Let’s check a number variable.
#include <iostream>
#include <typeinfo>
int main() {
int a = 20;
auto b = a * 2 ;
std::cout << "b has type -> "<<typeid(b).name()<<"\n";
return 0;
}
Output
b has type -> i
Let’s check a string variable.
#include <iostream>
#include <string>
#include <typeinfo>
int main() {
std::string message = "Hello from NoloWiz";
std::cout << message <<"\n";
std::cout << "message has type -> "<<typeid(message).name()<<"\n";
return 0;
}
Output
Hello from NoloWiz
message has type -> NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Let’s check a float pointer.
#include <iostream>
#include <typeinfo>
int main() {
float* percentage = nullptr;
std::cout << "percentage has type -> "<<typeid(percentage).name()<<"\n";
return 0;
}
Output
percentage has type -> Pf
Non-polymorphic object
#include <iostream>
#include <typeinfo>
struct Base {};
struct Derived : Base {};
int main() {
Derived drv;
Base& base = drv;
std::cout << "Reference to non-polymorphic base: " << typeid(base).name() << '\n';
return 0;
}
Output
Reference to non-polymorphic base: 4Base
Polymorphic object
So what about the polymorphic object? let’s check that.
#include <iostream>
#include <typeinfo>
struct Base { virtual void foo() {} }; //polymorphic
struct Derived : Base {};
int main() {
Derived drv;
Base& base = drv;
std::cout << "Reference to polymorphic base: " << typeid(base).name() << '\n';
return 0;
}
Output
Reference to polymorphic base: 7Derived
Expression as parameter
Let’s pass an expression as a parameter to typeid.
#include <iostream>
#include <typeinfo>
int main() {
int abc = 42;
const std::type_info& typeInfo = typeid((10 + abc) / 2.0);
std::cout <<"Type of expression (10 + abc) / 2.0 : "<<typeInfo.name();
return 0;
}
Output
Type of expression (10 + abc) / 2.0 : d