Null pointer call member function

Source: Internet
Author: User

Try to analyze the operation of the code is output:
#include <iostream>using namespace Std;class A {public:int m;void print () {  cout << "a\n";  } void B () { int sum = 0;for (int i=0; i<100; i++) {sum + = i;} printf ("sum=%d\n", sum);} void C (int n) {int sum = 0;for (int i=0; i<n; i++) {sum + = i;} printf ("sum=%d\n", sum); B ();} void M () {printf ("m=%d\n", M);}}; int main () {A *pa = 0;pa->print ();p a->b ();p a->c (1024x768);p a->m (); return 0;}

If you throw the code on the computer to run again, you can find that only the M method is called when the program will collapse, call other methods of the program is running normally, indicating no pressure!

Isn't it amazing?

The main reason for this analysis is that several other functions can be run independently of the object, because these methods do not involve any related items of the class, so it is understandable to run here.


In Summary, if a member function of a class is not used to a member variable of a class and does not use a member function that cannot be called individually, the member function can run normally with a null pointer call of that type . (although it doesn't seem to work, it seems like a fun way)

The output of the above results are:

asum=4950sum=523776sum=4950 Program Call m method Ben collapsed
The program annotations are analyzed as follows:
#include <iostream>using namespace Std;class A {public:int m;void print () {  cout << "a\n";  } void B () { int sum = 0;for (int i=0; i<100; i++) {sum + = i;} printf ("sum=%d\n", sum);} void C (int n) {int sum = 0;for (int i=0; i<n; i++) {sum + = i;} printf ("sum=%d\n", sum); B ();} void M () {printf ("m=%d\n", M);}}; int main () {A *PA = 0;//can normally call Pa->print ();p a->b ();p a->c (1024);//Use class-related items, call fail Pa->m ();//So if the class method and class called are not related , the call succeeds even if the class pointer is empty, return 0;}

Null pointer call member function

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.