Dynamic Cast - Example Code

Example Code

Suppose some function takes an object of type A as its argument, and wishes to perform some additional operation if the object passed is an instance of B, a subclass of A. This can be accomplished using dynamic_cast as follows.

#include // For std::bad_cast #include // For std::cerr, etc. class A { public: // Since RTTI is included in the virtual method table there should be at least one virtual function. virtual void foo; // other members... }; class B : public A { public: void methodSpecificToB; // other members. }; void my_function(A& my_a) { try { B& my_b = dynamic_cast(my_a); my_b.methodSpecificToB; } catch (const std::bad_cast& e) { std::cerr << e.what << std::endl; std::cerr << "This object is not of type B" << std::endl; } }

A similar version of my_function can be written with pointers instead of references:

void my_function(A* my_a) { B* my_b = dynamic_cast(my_a); if (my_b != NULL) my_b->methodSpecificToB; else std::cerr << "This object is not of type B" << std::endl; }

Read more about this topic:  Dynamic Cast

Famous quotes containing the word code:

    Wise Draco comes, deep in the midnight roll
    Of black artillery; he comes, though late;
    In code corroborating Calvin’s creed
    And cynic tyrannies of honest kings;
    He comes, nor parlies; and the Town, redeemed,
    Gives thanks devout; nor, being thankful, heeds
    The grimy slur on the Republic’s faith implied,
    Which holds that Man is naturally good,
    And—more—is Nature’s Roman, never to be
    scourged.
    Herman Melville (1819–1891)

    Faultless honesty is a sine qua non of business life. Not alone the honesty according to the moral code and the Bible. When I speak of honesty I refer to the small, hidden, evasive meannesses of our natures. I speak of the honesty of ourselves to ourselves.
    Alice Foote MacDougall (1867–1945)