Re: dynamic cast
On Sep 25, 2:28 pm, Sarang <sarangbah...@gmail.com> wrote:
Now the question is what are the benefits of using dynamic_cast here
instead of C-style cast, which can be re-interpret cast or static cast
depending upon the compiler knowledge about the conversion between the
types?
Thanks in advance,
Sarang.
struct A{};
struct B{virtual ~B();}
struct C:virtual A{};
struct D:A,C{};
A a;
B b;
C c;
D d;
A& ra=dynamic_cast<A&>(c);//dynamic_cast required by standard, no
choice
A&ra2=static_cast<A&>(d);//static OK, as long as you accept
responsibity for correct usage
B& rb =reinterpret_cast<B&>(a);//tell compiler that even though it
looks stupid, you know what you are doing
B&rb2=static_cast<B&>(a);////BOOM!! compiler error
B&rb3=dynamic_cast<B&>(c);////throw bad_cast
B&rb4=dynamic_cast<B&>(a);//compiler error, A is not polymorphic
B& rb5=(B&)d; //oops!! this is a reinterpret_cast, but probably should
have been a compile error
When you use C style cast, you are unsure just which variation you
will get -- it could either be reinterpret_cast, static_cast, or
const_cast. Cstyle cast is not allowed to do a dyanmic_cast.
The real advantage of C++ style casts is that you explictly tell the
compiler what type of cast you wish to perform,otherwise it is a
compier error. The surprise factor is taken out.
Lance
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]