The null class pointer calls the this pointer in the member function class.

Source: Internet
Author: User

Run the following code. What is the result?

Class

{

PRIVATE:

Int m_value;

Public:

A (INT value)

{

M_value = value;

}

Void print1 ()

{

Printf ("Hello World ");

}

Void print2 ()

{

Printf ("% d", m_value );

}

};

Int _ tmain (INT argc, _ tchar * argv [])

{

A * pA = NULL;

Pa-> print1 ();

Pa-> print2 ();

Return 0;

}

Analysis:

The answer is that the print1 call is normal and the Hello world is printed, but the program crashes when it runs to print2.

 

When you call print1, you do not need the PA address because the function address of print1 is fixed. The compiler will pass in a this pointer to print1, Which is null, but this pointer is not used in print1. As long as the program is running without accessing the memory that shouldn't be accessed, no error occurs, so it runs normally.

 

When running print2, this pointer is required to obtain the m_value value. The program crashes because this pointer is null.

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.