Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top