Questions regarding typeid operator

Hi everyone,

My understanding towards c++ is still shallow hence i can't fully understand how to fully use typeid() even if looking at msdn and cppreference. Any help is appreciated :)

When using typeid(), typing ".name()" behind it seems like a must rather than optional,
1. So why is ".name()" needed when using typeid()?

I do note that "." is used with ".name()",
2. So is "." a member access of object? If not, what is it?

The bracket in "name()" indicates that you can put something inside
3. does it have any use since i've only seen references with "name()" bracket being left out.
Last edited on
The typeid operator returns an object of type std::type_info. You can compare two std::type_info objects using == or != to check if the types are the same. I have never found a use for it myself but I guess it could be useful with templates.

The name function is indeed a member function of the std::type_info class. In order to call the function you need to use parentheses, as with all functions. It returns an implementation-defined name of the type so don't expect the names to be the same on two different compilers.

http://www.cplusplus.com/reference/typeinfo/type_info/
Last edited on
I understand most of it already, but still a bit confused on one part.

To use member access from object, it goes by the arragement of object.member_name right?

1. Why typeid() in typeid().name() has parenthesis even if it's an object, doesnt it make typeid() a function?
Last edited on
To use member access from object, it goes by the arragement of object.member_name right?

Yes, but object doesn't need to be a simple variable. It can be a any expression that returns an object (or a reference to an object).

1. Does that make typeid() an object? And an operator if it's typeid().name()?

No. typeid is an operator that returns an object. The name() function is called on the returned object.

Instead of writing
 
std::cout << typeid(type).name();
you can write
1
2
const std::type_info& typeInfo = typeid(type);
std::cout << typeInfo.name();

Note that I had to use a reference here because std::type_info can't be copied.

2. Why does typeid() in typeid().name(), an object has parenthesis, doesnt it make typeid() a function?

Techically typeid is an operator, but it doesn't really matter for the discussion if it was a function. The important thing is that it returns an object of type std::type_info.
typeid is an operator. The syntax of the operator is that you put parentheses around the entity that you want to get the type of.

The operator returns an object of type std::type_info. So when you write:

typeid(something).name()

you're calling the name() method of the std::type_info object that is returned by typeid(something).
Last edited on
That clarified a lot, thank you very much Peter87 and MikeyBoy :)
Topic archived. No new replies allowed.