Created
February 12, 2014 16:24
-
-
Save mikehelmick/8958979 to your computer and use it in GitHub Desktop.
Another reason I dislike C++ for teaching introductory programming.... this works
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> | |
| #include <cstdlib> | |
| class BadActor { | |
| public: | |
| BadActor() { | |
| this->value = 5; | |
| } | |
| int getValue() const { | |
| return value; | |
| } | |
| int get5() const { | |
| return 5; | |
| } | |
| private: | |
| int value; | |
| }; | |
| int main(int argc, char* argv[]) { | |
| BadActor* actor = NULL; | |
| // This line will result in a crash (actually on line 11) | |
| //std::cout << "getValue: " << actor->getValue() << std::endl; | |
| // This line doesn't crash | |
| std::cout << "get5() = " << actor->get5() << std::endl; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Right. W/ the non-virtual version the function call is statically bound, the this parameter is set to 0x0, but since it is never deferenced, no crash occurs.
With the virtual function, the function call must use dynamic dispatch, which fails in the lookup table.