DISCOVERING TYPES

The typeid operator enables you to discover the type of an expression. To obtain the type of an expression, you simply write typeid(expression), and this results in an object of type type_info that encapsulates the type of the expression. Suppose that you have defined variables x and y that are of type int and type double, respectively. The expression typeid(x*y) results in a type_info object representing the type of x*y, which by now you know to be double. Because the result of the typeid operator is an object, you can’t write it to the standard output stream just as it is. However, you can output the type of the expression x*y like this:

cout << "The type of x*y is " << typeid(x*y).name() << endl;

This will result in the output:

The type of x*y is double

You will understand better how this works when you have learned more about classes and functions in Chapter 7. You won’t need to use the typeid operator very often, but when you do need it, it is invaluable.

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.