Last active
August 29, 2015 14:01
-
-
Save tejainece/33f465829b55753623f0 to your computer and use it in GitHub Desktop.
C++: Static and dynamic cast
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 <iostream> | |
| using namespace std; | |
| class Base { | |
| public: | |
| virtual void print() { | |
| cout << "in base" << endl; | |
| } | |
| virtual ~Base() { | |
| cout << "Boom destructed" << endl; | |
| } | |
| }; | |
| class Derived1 : public Base { | |
| public: | |
| int var1 = 1; | |
| virtual void print() { | |
| cout << "1" << endl; | |
| } | |
| }; | |
| class Derived2 : public Base { | |
| public: | |
| int var1 = 2; | |
| virtual void print() { | |
| cout << "2" << endl; | |
| } | |
| }; |
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
| Derived1 *d1p1 = dynamic_cast<Derived1 *>(bp1); |
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
| if(d1p1 != NULL) { | |
| d1p1->print(); | |
| } else { | |
| cout << "Couldn't cast" << endl; | |
| } |
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
| Base b; | |
| Derived1 d1; | |
| Base *bp1 = dynamic_cast<Base *>(&d1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment