'Pointer obejct function call without instantiating it [duplicate]

I don't understand how does following code called f() function successfully. As object b is not instantiated using new keyword. Please help and Thanks in advance for answers.

#include <iostream>
using namespace std;

class A{ public:
    void f(){cout<<"f";}
};

int main()
{
    A *b;
    delete b;
    b->f();

    return 0;
}


Solution 1:[1]

I don't understand how does following code called f() function successfully.

The program has undefined behavior since b is not initialized and is also not pointing to memory allocated by new.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.

For example, here the program doesn't crash but here it crashes.

To solve this make sure that the pointer b is initialized and is pointing to memory allocated by new.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoop Rana