Skip to content

Instantly share code, notes, and snippets.

@mikehelmick
Created February 12, 2014 16:24
Show Gist options
  • Select an option

  • Save mikehelmick/8958979 to your computer and use it in GitHub Desktop.

Select an option

Save mikehelmick/8958979 to your computer and use it in GitHub Desktop.
Another reason I dislike C++ for teaching introductory programming.... this works
#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;
}
@mikehelmick
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment