Reputation: 151
I cannot get typeid function correctly. Am I missing something
Code:
class A
{
public:
int a1;
A()
{
}
};
class B: public A
{
public:
int b1;
B()
{
}
};
int main()
{
B tempb;
A tempa;
A * ptempa;
ptempa = &tempb;
std::cout << typeid(tempb).name() << std::endl;
std::cout << typeid(tempa).name() << std::endl;
std::cout << typeid(*ptempa).name() << std::endl;
return 0;
}
It always prints:
Class B Class A Class A
I am using VS2010 for my project
Upvotes: 9
Views: 9664
Reputation: 158449
The object it points to must be polymorphic for this to work as you expect. If A
had virtual
methods than your code would have work as expected, for example adding a virtual destructor, which I demo live here using gcc.
Quote form the C++ draft standard section 5.2.8
Type identification paragraph 2 says:
When typeid is applied to a glvalue expression whose type is a polymorphic class type (10.3), the result refers to a std::type_info object representing the type of the most derived object (1.8) [...]
Which applies to the case where we have a virtual
method, in your case you do not have a polymorphic type so paragraph 3 applies:
When typeid is applied to an expression other than a glvalue of a polymorphic class type, the result refers to a std::type_info object representing the static type of the expression
So you will get the static
type back which is A
.
Just to be a little more complete section 10.3
Virtual functions says:
Virtual functions support dynamic binding and object-oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.
Upvotes: 10
Reputation: 1389
Having thought about it while mowing the lawn... A pointer cannot know what type of object it is pointing at. The type information is stored with the pointer and this is not changed by pointing at a derived class (B). So you need a typecast to change the type of a pointer and the output IS as expected.
Upvotes: 0
Reputation: 76235
The problem is that A
has no virtual functions, so is not treated as a polymorphic type. As a result, typeid
looks up the declared type of the pointer, not the actual type of the object that it points to.
Upvotes: 21