Created
June 7, 2014 10:33
-
-
Save Joshhua5/d9f87121f33f845d6be9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
class A{ | |
public: | |
virtual int getInt() { return 3; } | |
}; | |
class B : public A{ | |
public: | |
int getInt() { return 2; } | |
}; | |
class C : public A{ | |
public: | |
int getInt() { return 4; } | |
}; | |
void main(){ | |
C c; | |
B b; | |
A* a = &b; | |
if (dynamic_cast<B*>(a)){ | |
std::cout << dynamic_cast<B*>(a)->getInt() << std::endl; | |
} | |
// if the object can't be converted to the type C, | |
// because it never inherited it then it'll return nullptr | |
if (dynamic_cast<C*>(a)){ | |
std::cout << dynamic_cast<B*>(a)->getInt() << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment