-1

Why the below program is not producing a runtime error!!

#include <iostream>
using namespace std;

class temp
{
    public:
       void func(){cout<<"it works"<<endl;}
};

 int main()
{
   temp* ptr = NULL;
   ptr->func();
   return 0;
}

this code prints "it works" why?? ptr is accessing NULL memory it should crash.

if the explanation is that class has no member variables , then i tried the following code and it also works why??

#include <iostream>
using namespace std;

class temp
{
   int i;
    public:
       void func(){cout<<"it works"<<endl;}
};

 int main()
{
   temp* ptr = NULL;
   ptr->func();
   return 0;
}
luck
  • 165
  • 1
  • 10

2 Answers2

1

class temp is trivial and has no special hidden information like a vtable that needs this to screw things up on func's method call and void func(){cout<<"it works"<<endl;} makes no use of this, so it never realizes this is NULL and accesses outside bounds.

It should be noted that even if this was used, there is no certainty of a crash. The program could declare undefined behaviour and brutally murder a unicorn instead.

user4581301
  • 33,082
  • 7
  • 33
  • 54
1

Undefined behavior.

A C++ program is allowed to do pretty much anything it wants when the standard says the behavior is undefined. And one must understand that undefined behavior includes "pretend that everything is working fine".


What probably happens here is that the compiler recognizes that, in any situation where behavior is well-defined, calling func() will result in printing "it works". Since it's allowed to do anything it wants when behavior is ill-defined, it does the simplest thing (which is also the most efficient in the defined cases) and always results in printing "it works" regardless of whether or not it's being invoked on a valid object.