This have been asked in the interview.
How to write own dynamic_cast. I think, on the basis of typeid’s name function.
Now how to implement own typid? I have no clue on it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There is a reason you don’t have any clue,
dynamic_castandstatic_castare not likeconst_castorreinterpret_cast, they actually perform pointer arithmetic and are somewhat typesafe.The pointer arithmetic
In order to illustrate this, think of the following design:
An instance of
Derivedshould look something like this (it’s based on gcc since it is actually compiler dependent…):Now think of the work necessary for casting:
DerivedtoBase1does not require any extra work, they are at the same physical addressDerivedtoBase2necessitates to shift the pointer by 2 bytesTherefore, it is necessary to know the memory layout of the objects to be able to cast between one derived object and one of its base. And this is only known to the compiler, the information is not accessible through any API, it’s not standardised or anything else.
In code, this would translate like:
And that is, of course, for a
static_cast.Now, if you were able to use
static_castin the implementation ofdynamic_cast, then you could leverage the compiler and let it handle the pointer arithmetic for you… but you’re still not out of the wood.Writing dynamic_cast ?
First things first, we need to clarify the specifications of
dynamic_cast:dynamic_cast<Derived*>(&base);returns null ifbaseis not an instance ofDerived.dynamic_cast<Derived&>(base);throwsstd::bad_castin this case.dynamic_cast<void*>(base);returns the address of the most derived classdynamic_castrespect the access specifications (public,protectedandprivateinheritance)I don’t know about you, but I think it’s going to be ugly. Using
typeidis not sufficient here:The issue here is that
typeid(base) == typeid(Derived) != typeid(Intermediate), so you can’t rely on that either.Another amusing thing:
static_castdoesn’t work when virtual inheritance is involved… so we’ve go a problem of pointer arithmetic computation creeping in.An almost solution
You need some little things in the constructor:
So, let’s check:
virtualinheritance ? it should work… but not testedGood luck to anyone trying to implement this outside of the compiler, really 😡