Reputation: 2663
I have the following code:
#include <iostream>
#include <string>
class BaseNode {
public:
BaseNode(std::string s) {
std::cout << "Called BaseNode(string)" << std::endl;
}
BaseNode() {
std::cout << "Called BaseNode()" << std::endl;
}
void count(int num) {
std::cout << "count() in BaseNode " << num << std::endl;
}
};
class MyNode : public BaseNode {
public:
MyNode() : BaseNode("test") {
std::cout << "Called MyNode()" << std::endl;
}
void count(int num) {
std::cout << "count() in MyNode " << num << std::endl;
}
};
int main(int argc, char * argv[]) {
MyNode *mn;
mn->count(6);
return 0;
}
To my surprise this compiles and prints "count() in MyNode 6". But should it work?
If I declare count as virtual in the base class
class BaseNode {
public:
BaseNode(std::string s) {
std::cout << "Called BaseNode(string)" << std::endl;
}
BaseNode() {
std::cout << "Called BaseNode()" << std::endl;
}
virtual void count(int num) {
std::cout << "count() in BaseNode " << num << std::endl;
}
};
I get "Segmentation Faul" on the count call. What is going on behind the scenes here?
Upvotes: 0
Views: 63
Reputation: 15446
MyNode *mn;
creates a Wild Pointer, or a Dangling Pointer--that is, one that points to memory you don't own. So trying to dereference the pointer and fetch that memory is indeed Undefined Behavior.
What is going on behind the scenes here?
Since this is Undefined Behavior, we don't know. The results here are determined by whatever your compiler decided to do, which could very well include making "demons fly out of your nose."
Upvotes: 3