0

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;
}
  • 3
    `delete b;` is already wrong, since at this point `b` is not even initialized, let alone pointing at memory allocated with `new`. – Karl Knechtel Apr 29 '22 at 15:53
  • 1
    The short answer is that if you want code that is wrong to *consistently not appear to work*, then C and C++ are not viable languages for you. – Karl Knechtel Apr 29 '22 at 15:54
  • 1
    In the name of efficiency, C++ assumes the programmer isn't out to shoot themselves in the foot and makes very few checks to ensure the programmer's not doing something foolish. – user4581301 Apr 29 '22 at 16:13

1 Answers1

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.

Jason
  • 36,170
  • 5
  • 26
  • 60