0

How does below program prints "Show Called" ? I guess it should have been run-time error since value of obj ptr is NULL.

#include<iostream>
using namespace std;

   class ex
    {
        int i;

    public:
        ex(int ii=0):i(ii) {}

        ~ex(){cout<<"dest"<<endl;}

        void show()
        {
            cout<<"Show called";
        }

    };

    int main()
    {
        ex *obj = NULL;
        obj->show();

        return 0;
    }
Rohit
  • 6,941
  • 17
  • 58
  • 102

3 Answers3

0

You have to know, how the methods are called.

ex::show();
(...)

obj->show();

Is (mostly probably) translated by your specific compiler to:

show(ex * this);
(...)

show(obj);

And since you do not use this inside, there is no reason for the exception to be thrown...

I stressed out your specific compiler, because:

C++ standard, chapter 8.3.2, References

[ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by indirection through a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. —end note ]

Community
  • 1
  • 1
Spook
  • 25,318
  • 18
  • 90
  • 167
  • agreed, but it will throw an exception if you try to acces any public data member through that object as there is no memory allocated to that object. – Saksham Jun 18 '13 at 11:09
  • @Saksham it doesn't *have* to throw an exception. It is just undefined behaviour. – juanchopanza Jun 18 '13 at 11:14
  • @Saksham juanchopanza is right: accessing the members again would require to dereference a null pointer, which - by standard - is undefined (and - by design of a specific compiler - *may not* result in exception). However any sane compiler should throw an exception in such case IMO :) – Spook Jun 18 '13 at 11:16
  • Thanks all for letting me know of what I am aware of. I had added this comment for @powerpc to give a better insight of what may cause a compile time error :) – Saksham Jun 18 '13 at 12:21
0

In your example the method is non virtual. So it is implemented as a normal function. As you don't dereferernce this there is no problem. Would your method be virtual you would call something like this->__vtable[0](this) which would not work because you would dereference 0.

Jan Herrmann
  • 2,717
  • 17
  • 21
0

As you are not accessing any public data member, it will not throw any exception.

But it will throw an exception if you try to acces any public data member through that object as there is no memory allocated to that object.

Saksham
  • 9,037
  • 7
  • 45
  • 73
  • 1
    Since dereferencing a null pointer is an **undefined behavior**, it actually *may* throw exception - depending on used compiler. His particular compiler doesn't. – Spook Jun 18 '13 at 11:13