Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Created May 31, 2012 16:59
Show Gist options
  • Save stephenmm/2844744 to your computer and use it in GitHub Desktop.
Save stephenmm/2844744 to your computer and use it in GitHub Desktop.
Using dynamic_cast in a few examples to show how its used. (polymorphic)
// g++ dynamic_cast_example.cpp -o dynamic_cast_example.x && dynamic_cast_example.x
#include <iostream>
using namespace std;
class A { public: virtual string class_string() { return "Class A"; } };
class B : public A { public: virtual string class_string() { return "Class B"; } };
class C : public A { public: virtual string class_string() { return "Class C"; } };
class D : public C { public: virtual string class_string() { return "Class D"; } };
// dynamic_cast returns NULL if the cast is impossible and the type is a pointer
void cast_my_ptr( A* pA, string s ) {
B* pB = dynamic_cast<B*>(pA);
C* pC = dynamic_cast<C*>(pA);
D* pD = dynamic_cast<D*>(pA);
if (pA) cout << s << ":pA = " << pA->class_string() << endl;
if (pB) cout << s << ":pB = " << pB->class_string() << endl;
if (pC) cout << s << ":pC = " << pC->class_string() << endl;
if (pD) cout << s << ":pD = " << pD->class_string() << endl;
};
void cast_my_ref_a2a( A& rAi, string s ) {
A& rA = dynamic_cast<A&>(rAi);
cout << s << ":rA = " << rA.class_string() << endl;
};
void cast_my_ref_a2b( A& rA, string s ) {
B& rB = dynamic_cast<B&>(rA);
cout << s << ":rB = " << rB.class_string() << endl;
};
void cast_my_ref_a2c( A& rA, string s ) {
C& rC = dynamic_cast<C&>(rA);
cout << s << ":rC = " << rC.class_string() << endl;
};
void cast_my_ref_a2d( A& rA, string s ) {
D& rD = dynamic_cast<D&>(rA);
cout << s << ":rD = " << rD.class_string() << endl;
};
// dynamic_cast throws exception if the cast is impossible and the type is a reference
void cast_my_ref( A& rA, string s ) {
B& rB = dynamic_cast<B&>(rA);
C& rC = dynamic_cast<C&>(rA);
D& rD = dynamic_cast<D&>(rA);
};
int main() {
A aobj;
B bobj;
C cobj;
D dobj;
A* pAobj = &aobj;
A* pBobj = &bobj;
A* pCobj = &cobj;
A* pDobj = &dobj;
cast_my_ptr(pAobj,"pAobj");
cast_my_ptr(pBobj,"pBobj");
cast_my_ptr(pCobj,"pCobj");
cast_my_ptr(pDobj,"pDobj");
A& rAobj = aobj;
A& rBobj = bobj;
A& rCobj = cobj;
A& rDobj = dobj;
cast_my_ref_a2a(rAobj,"rAobj");
cast_my_ref_a2b(rBobj,"rBobj");
cast_my_ref_a2c(rCobj,"rCobj");
cast_my_ref_a2d(rDobj,"rDobj");
cast_my_ref(rAobj,"rAobj");
cast_my_ref(rBobj,"rBobj");
cast_my_ref(rCobj,"rCobj");
cast_my_ref(rDobj,"rDobj");
}
// Output:
// pAobj:pA = Class A
// pBobj:pA = Class B
// pBobj:pB = Class B
// pCobj:pA = Class C
// pCobj:pC = Class C
// pDobj:pA = Class D
// pDobj:pC = Class D
// pDobj:pD = Class D
// rAobj:rA = Class A
// rBobj:rB = Class B
// rCobj:rC = Class C
// rDobj:rD = Class D
// terminate called after throwing an instance of 'std::bad_cast'
// what(): St8bad_cast
// Abort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment