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
The typeid operator allows the type of an object to be determined at run time. The result of typeid is a const type_info& . The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.
The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. This operator, along with the dynamic_cast operator, are provided for runtime type identification (RTTI) support in C++.
Since typeid is applied to a type rather than an object, there is no runtime type information, so that overhead won't be a problem.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With