Call child method with reinterpret_cast or not ?

I have class A and method a().
I have class B : public A and new method b().
I can call b from A like
reinterpret_cast<B*>(this)->b();
If I am 100% sure that this A instance is B, not just A, is it
1) always safe to do like this?
2) faster than virtual call?
Last edited on
¿why is your base class aware of its derived classes?
I can ask, but it has no Talk method. :[

You say it's safe for sure, did I get you right?
Last edited on
> reinterpret_cast<B*>(this)->b();
> If I am 100% sure that this A instance is B, not just A, is it

> 1) always safe to do like this?

No, it is not safe.

If it is guaranteed that the dynamic type of the object pointed to by this is B or a derived class of B (and B does not inherit virtually from A), static_cast<B*>(this)->b(); is safe.


> 2) faster than virtual call?

Yes. Particularly if B::b() is inlineable. Marginally otherwise.

Thank u!
I don't see any real use of it in my plans though.))
(This is not much useful at all)
Last edited on
> This is not much useful at all

True.

With polymorphic classes: favour virtual functions over casts of any kind, dynamic_cast over static_cast

With any type: favour static_cast over reinterpret_cast
Topic archived. No new replies allowed.