The following code compiles correctly and get the mysterious output:
special Investment function
00000000
(Environment: C++ VS2010)
#include <iostream>
#include <vector>
using namespace std;
class Security {
public:
virtual ~Security() {}
};
class Stock : public Security {};
class Investment : public Security {
public:
void special() {
cout << "special Investment function" << endl;
}
};
int main() {
Security* p = new Stock;
dynamic_cast<Investment*>(p)->special();
cout << dynamic_cast<Investment*>(p) << endl;
return 0;
}
How could it be? Dereferencing a NULL pointer and get a “correct” output instead of crash?
Is it a special “characteristic” of VS2010?
Now I see. I did a test and it appears that dereferencing “this” in “special” function cause the program to crash.
Thanks for your help.
Dereferencing a null pointer is undefined behavior – you can get unexpected results. See this very similar question.
In this case
Investment::special()is called in a non-virtual way, so you can think the compiler just creates a global functionand calls it passing a null
thispointer as the implicit parameter.You should not rely on this.