开发者

typeid , dynamic casting (upcast) and templates [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

开发者_运维问答

Closed 8 years ago.

Improve this question

I have few questions regarding dynamic casting , typeid() and templates

1) How come typeid does not require RTTI ?

2) dynamic_cast on polymorphic type:

  • When I do downcast (Base to Derive) with RTTI - compilation passes

    When RTTI is off - I get a warning (warning C4541: 'dynamic_cast' used on polymorphic type 'CBase' with /GR-; unpredictable behavior may result)

  • When I do upcast (Derive to Base), with or without RTTI - compilation passes smoothly

What I don't understand is why when I do upcast and RTTI is off - I don't get any warning/error!

3) dynamic_cast on NON polymorphic type:

  • When I do downcast with or without RTTI - compilation fails (error C2683: 'dynamic_cast' : 'CBase' is not a polymorphic type)

BUT

  • When I do upcast with or without RTTI - compilation passes smoothly.

How come on upcast on NON polymorphic type passes w/o RTTI ?

4) Does 'inline' in front of a template function has any effect, i.e. when the compiler compiles the function and see it is 'inline' it will actually treat the function as inline or it is ignored?

Thank you very much for the assistance David


1) It does require RTTI. At least if you are using it on polymorphic classes...which is really its purpose.

2) If you don't have RTTI on the dynamic_cast can't check to see if the object you are casting is actually an object type you are casting to. This is the difference between dynamic_cast (essentially) and static_cast. Static_cast does not check this, and thus is less 'safe' but faster. Thus if you have no RTTI, it CAN'T do a dynamic cast when you're downcasting

Upcasting is safe because you can determine types at compile time, and thus you can upcast with dynamic_cast to the base class.

3) dynamic_cast downcasting is for polymorhpic types (eg types with a virtual function in them), and thus if the class isn't polymorphic its not going to work. So if CBase doesn't have a virtual function you can't use dynamic_cast with it.

Same reason as 2 for the upcasting.

I think you should read a bit on what the different casts are for.

http://www.cplusplus.com/doc/tutorial/typecasting/

4) Yes it will compile it as inline.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜