Implicit cast from derived to base == static_cast
Hello,
Question-1:
Recently i was asked a question on the following lines...
1. class A {};
2. class B : public A {};
3. A *anA = 0;
4. B *aB = new B;
5. anA = aB;
6. anA = dynamic_cast<A*>(aB);
What is the difference between lines 5 and 6? Are they both same
semantically?
AFAIK, implicit cast in C++ has semantics of a static_cast. i.e. it is
done solely with compile-time information.
Question-2:
Can i vindicate my understanding of Question-1 above with the
following code as proof!
<snip>
1. class A{
2. };
3. class B {
4. public:
5. virtual ~B() {} // just to make this class polymorphic
6. };
7. int main(){
8. A *anA = 0;
9. B *aB = new B;
10. //anA = aB;
11. //anA = static_cast<A*>(aB);
12. anA = dynamic_cast<A*>(aB);
13. if(!anA)
14. std::cout<<"There you go!"<<std::endl;
15. return 0;
16. }
<\snip>
Lines 10 and 11 fail to compile. Line 12 suceeds. This is bcoz
dynamic_cast fails at runtime if done on unrelated classes!
static_cast will say the same but at compile time. So the deafult
casting also has semantics of a static_cast.
Question-3:
What sections of the C++ standard deal with implicit casting and its
underlying implementation. Is it unspecified / implementation-defined?
Question-4:
In the context of the above question, is it possible to have a class
hierarchy, wherein a static_cast would succeed and a dynamic_cast
would fail for the same cast?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]