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.