Hi guys,

i am quite newbie to c++. Is there any way to know object class. I have a object and i want to know the exact class name for that.

Recommended Answers

All 5 Replies

Use typeid keyword.

cout <<  typeid(p).name();
commented: Yes, typeid() is perfect :) +9

Use typeid keyword.

cout <<  typeid(p).name();

And include the typeinfo header: #include <typeinfo> :)

Not so fast. Although the solution provided works well, always ask yourself why do you need to know the name of the class?
typeid() is a slow construct, it is evaluated at runtime. (Though the most compiler optimize it so as it can be determined at the compile time. This usually applies to object which do not emits polymorphism and complex inheritance)

Also note that type_info::name() will not yield same result on different implementations. My implementations prints 1A due to following code:

#include<iostream>
#include<typeinfo>
class A{};
int main()
{
    A a;
    std::cout<<typeid(a).name();
}

So, the bottom line is, that you shouldn't be needing type_info until your doing some dirty (albeit serious) work. Can we know why do you need to know the name of the object at the runtime?

Thanks for your answer guys...
I have a state machine implemented in c++. I have base class pointer that points to different stats class object at run time. At some point i need to know through this base pointer to which stat my base pointer is pointing to so that i can take some action.
For example
my base pointer can point to either active,pending or inactive state class object.

if my base pointer is pointing to active class object then i need to avoid some action. So i was looking answer for this question. If there is something i can use from inbuilt c++ functionality otherwise i have to put some strings in base class saying what is the state of base pointer.

thanks

So, what's stopping you from marking this thread as solved?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.