- The typeid operator is used to
determine the type of an object.
It returns a typeinfo object, which
is defined in the typeinfo header.
Let's take a look at how this works.
Here's a copy of typeid.cpp from
Chapter Four of the Exercise Files.
You notice here, we have an include typeinfo.
That's the header that has the typeinfo object,
which is returned by the typeid operator.
So we declare a couple of simple structures.
They're identical, but they're different structures
there's struct A and struct B,
and a couple of variables of each.
We've got a1, a2, b1, and b2
of types A and B, respectively.
And here we compare the typeid
of the object a1 to the typeid of the structure,
or class, A, and if they're the same, it prints "same",
and if they're different, it prints "different".
So we'll go ahead and we'll build and we'll run this,
and we see that they are the same.
The object a1 is indeed of type A.
And so the typeid on both of those values,
on the object itself and the type, or class,
return exactly the same typeinfo object.
And so we get "same" because they're identical,
and if they were not identical, we would get "different".
And so if I compare it to type B
and build and run, you see it says "different".
So that is actually pretty useful.
If you want to know the type of a variable,
you can compare the typeid of the variable
with the typeid of its type.
There's also a name method to the typeinfo object.
And so, I can do this I can say printf type is .
And when I build and run, you'll notice
that I get this value 1b, and if you're not on a Mac,
if you're on Windows or some other operating system,
or your using some other compiler,
you would get an entirely different value.
And sometimes it's like a whole bunch
of numbers and letters there's really no standard to it.
And so it's not a terribly useful value.
It's very implementation dependent.
And most of the time, all you really want to know
is if it's the same as a given type.
And so the comparison as we have up here in line 15
is far more useful, and it's going to
work best for you under most circumstances.
So the typeid operator may be used
to determine the type of an object.
While you can return a string representation of the type
it's often easier to just compare the results
of typeid to determine the type of an object.