dynamic_cast

Discussion in 'C++' started by ballurohit, Feb 29, 2012.

  1. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    I have roughly gone thro' the defination. But still I am in confusion as to how
    I can implement in C++. The example is as follows:

    // dynamic_cast
    #include <iostgream.h>
    #include <exception> // the header file I do not know
    class CBase{virtual void dummy() {} };
    class CDerived: public CBase {int a;};
    int main() {
    try {
    CBase *pba=new CBase;
    CDerived *pd;
    pd=dynamic_cast<CDerived* >(pba);
    if (pd==0) cout << "Null pointer on first type-cast" << endl;
    pd=dynamic_cast <CDerived* >(pbb);
    if (pd==0 cout << "Null pointer on second type-cast" <<endl;
    } catch (exception& e) {cout <<"Exception: " <<e.what();}
    return 0;
    }
     
  2. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    Kindly give me some hint for the said example.
     
  3. ballurohit

    ballurohit New Member

    Joined:
    Nov 18, 2011
    Messages:
    43
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    retired
    Location:
    Gujarat
    I wanted a brief about dynamic_cast. so pl. have ur valuable comments on it
    BNRohit
     
  4. johnBMitchell

    johnBMitchell New Member

    Joined:
    Feb 17, 2011
    Messages:
    38
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    CA, USA
    Home Page:
    http://www.spinxwebdesign.com/
    Dynamic cast is a concept of Type conversions. It is used when we don’t know about type of object is. So at that time it performs type-safe downcasts where one of type is converting into some other types dynamically. It is used only with pointers objects and references to objects.
    Example of Dynamic cast
    if(JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
    ...
    } else if(ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
    ...
    }
    Hop this will give you some guideline.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice