Let's take a look at the procedure first: (this is also the pen question I met)
# Include <iostream> using namespace STD; Class test1 {public: void func () {cout <"test1" <Endl ;}}; class Test2 {public: test2 (INT I = 0): Val (I) {} void func () {cout <Val <Endl;} PRIVATE: int Val ;}; class test3 {public: virtual void func () {cout <"test3" <Endl ;}; int main (void) {test1 * P1 = NULL; P1-> func (); // output: Why is Test2 * P2 = NULL? P2-> func (); // Why is an error reported? test3 * P3 = NULL; P3-> func (); // report error, why return 0 ;}
Why can test1 be output? Because the address of P1 is not required at this time, because the address of the func function in test1 is fixed, the compiler imports a this pointer to func, Which is null, but in P1-> func () this pointer is not used; this is like passing an incorrect real parameter to a function, but the corresponding type parameter is not used in the function sometimes, the output result is not affected.
This explains why Test2 cannot be output, because its func uses the member variable Val, so if this pointer does not point to this object, it cannot get the member variable, errors will naturally occur.
Why is test3? Because it has virtual functions, virtual function tables are required. vptr is initialized in the constructor, while P2 is not constructed. Therefore, P2-> func (); the call fails.