Skip to content

Instantly share code, notes, and snippets.

@Joshhua5
Created June 7, 2014 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joshhua5/d9f87121f33f845d6be9 to your computer and use it in GitHub Desktop.
Save Joshhua5/d9f87121f33f845d6be9 to your computer and use it in GitHub Desktop.
#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