Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Cast working on unrelated types

#include <iostream> 
using namespace std; 
class X{ 
     public: 
     virtual void f(){} 
}; 

class Y { 
     public: 
     virtual void g() {} 
}; 

int main() 
{ 
     X * x = new X(); 
     Y* y = dynamic_cast<Y*>(x); //A 
     // Y* y = static_cast<Y*>(x);  //B 
     cout << y << endl; 
} 

A compiles whereas B doesn't. I understand why B doesn't get compiled but why does A get compiled although X and Y are completely unrelated types?

like image 836
M.C Avatar asked Oct 11 '10 15:10

M.C


2 Answers

This is why dynamic_cast is allowed between unrelated types:

class X{ 
     public: 
     virtual void f(){} 
}; 

class Y { 
     public: 
     virtual void g() {} 
};

class Z : public X, public Y {};

int main()
{ 
     X* x = new Z(); 
     Y* y = dynamic_cast<Y*>(x); // compiles and yields non-null pointer
} 
like image 171
Ben Voigt Avatar answered Oct 11 '22 17:10

Ben Voigt


The dynamic cast uses the runtime type information. So this is legal do this case but it will return a null pointer. The static cast is evaluated by the compiler.

like image 29
mkaes Avatar answered Oct 11 '22 16:10

mkaes