开发者

Typeid behavior in c++

开发者 https://www.devze.com 2023-02-05 12:38 出处:网络
Can someone explain tome why this code prints Base , Derived but if i omit the f function from Base prints Base , Base ?

Can someone explain to me why this code prints Base , Derived but if i omit the f function from Base prints Base , Base ?

#include <iostream>
#include <cstdio>
using namespace std; 

class Base;
void testClassType (Base& b);
class Base
{
 virtual void f(){};
};

class Derived :public Base
{
};

int main ()
{
 Base b;
 Derived d开发者_如何学Python;
 testClassType(b);
 testClassType(d);

}
 void testClassType(Base& b)
 {
  cout<<endl<<"It is:"<<typeid(b).name();
 }


By definition of typeid, it returns the dynamic type of the expression for polymorphic types and static type of the expressions for non-polymorphic types.

A polymorphic type is a class type that has at least one virtual function.

In your case, when you call testClassType(d), expression b inside testClassType function has static type Base and dynamic type Derived. However, without a single virtual function in Base, typeid will always report the static type - Base. Once you make your Base polymorphic, the code will report the dynamic type of b, which is Derived.

On top of that, as Oli correctly noted in the comments, the result of type_info::name() method is not guaranteed to contain any meaningful information. It can just return the same "Hello World" string for all types.


A class with at least one virtual member function is called a polymorphic class.

Each instance of a polymorphic class has (somehow) associated, at runtime, the original class used for instantiation. This is used by e.g. typeid. And also for calls of virtual member functions.

When you make the class non-polymorphic by removing f, then all that's known in testClassType is that it's a Base. No run-time checking of the type.

Cheers & hth.,

0

精彩评论

暂无评论...
验证码 换一张
取 消