Can a member function of an object be called when the pointer does not point to an actual object?

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.