Why to opt for dynamic_cast in C++ -


this question has answer here:

consider below code:

#include <iostream>  using namespace std;  class base{     int i;     public:     virtual bool basetrue() {return true;}     base(int i) {this->i=i;}     int get_i() {return i;}     };  class derived : public base{     int j;     public:     derived(int i,int j) : base(i) {this->j=j;}     int get_j() {return j;}     };  int main() {     base *bp;     derived *pd,dob(5,10);      bp = &dob;      //we trying cast base class pointer derived class pointer     cout << bp->get_i() << endl;     cout << ((derived *)bp)->get_j() << endl;**//here1**      pd=dynamic_cast<derived*> (bp); **//here2**     // if base class not polymorphic     //throw error     //error: cannot dynamic_cast `bp' (of type `class base*')     //type `class derived*' (source type not polymorphic)      cout << pd->get_j() << endl;**//here2**      //now try cast derived class pointer base class pointer      base *pb;     derived *dp,dbo(50,100);     dp = &dbo;       cout << ((base *)dp)->get_i() << endl;**//here3**     //cout << ((base *)dp)->get_j() << endl;     //throws error test.cpp:42: error: 'class base' has no member named 'get_j'      pb =  dynamic_cast<base * > (dp); **//here4**     cout << pb->get_i() << endl; **//here4**     //cout << pb->get_j() << endl;     //throws error test.cpp:47: error: 'class base' has no member named 'get_j'       return 0;     } 

the output

gaurav@gaurav-pc /cygdrive/d/glaswegian/cpp/test $ ./test 5 10 10 50 50 

the way casting (line here1 , here2 ) & (here3 & here4), difference between 2 ? both produce same output, why go dynamic_cast

dynamic_cast "safe" in either throws exception or returns null when doing "bad" (or, nawaz says, doesn't compile, because type sufficiently bad compiler can see going wrong)

the (derived *)... form act similar reinterpret_cast<derived *>(...), "unsafe" - convert 1 pointer other pointer type, whether yields meaningful result or not. it's problem if behaves "badly".

you can this:

int x = 4711;  derived *dp = (derived *)x;  cout << dp->get_j();  

the compiler may moan bit size of integer, otherwise, compile code. won't @ run, if does, result nothing "useful".


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -