0

The below code runs perfectly fine and prints "Executed".

I don't understand how this can be possible if pointer "p" is NULL ??

#include <iostream>
using namespace std;
class Foo
{
    public:
    Foo(int i = 0){ _i = i;}
    void f()
    {
        cout << "Executed"<<endl;
    }
    private:
    int _i;
};
int main()
{
    Foo *p = NULL;
    p -> f();
}
ali
  • 529
  • 4
  • 26
  • 2
    As the old saying goes, undefined behaviour is undefined. – molbdnilo Jun 25 '20 at 17:21
  • A lot of the times in C++, failing to follow the rules is not required to explicitly crash or fail. Anything can happen, including exactly what you expected. It is still an error. – François Andrieux Jun 25 '20 at 17:22
  • 1
    Why would you say that it "runs fine" when it didn't do what you expected? Generally, we only describe code as "running fine" if it does what we expected. – David Schwartz Jun 25 '20 at 17:24
  • 1
    Note that once you go UB, there's no going back. You cannot really check for `this == nullptr` inside the member function, compilers will happily remove the if. – Guillaume Racicot Jun 25 '20 at 17:25
  • thanks for the comments. But if the pointer is literally is NULL, how it makes the call?? I guess its just unexpected behaviour – ali Jun 25 '20 at 17:37
  • 1
    @ali In a typical implementation the pointer is effectively passed as a hidden parameter to a method. Obviously NULL can be passed as a parameter without any problem. If you examined `this` inside the `f` method you might find that it is also NULL. – john Jun 25 '20 at 17:43
  • So shall I delete the question? – ali Jun 25 '20 at 17:54
  • @ali no. keep it there. Your question will likely be found through searches and newcomers will be rerouted to the other already answered question. – Guillaume Racicot Jun 25 '20 at 19:24
  • 1
    @ali Your code is a bit equivalent to `f(nullptr)` as if `f` was `f(Foo*)`. You can still call `f`, it's just that the hidden `this` parameter is null. However, be aware to not rely on this as it is undefined behavior to call a member function on a null object. It could crash if for example you try to access a data member. For a non member function, the behavior is defined even if some parameter are null. – Guillaume Racicot Jun 25 '20 at 19:27
  • 1
    @ali If you're curious, I suggest you to try [reading the assembly here](https://godbolt.org/z/xoYXq2), and try it with virtual functions. – Guillaume Racicot Jun 25 '20 at 19:32
  • Thanks for the link – ali Jun 25 '20 at 19:36

0 Answers0