1

Lets say I have the following class

struct FooList {
    int data;
    FooList *next;

    // basic constructor
    FooList(int d, FooList *n): data(d), next(n) {}
    // basic destructor
    ~FooList() { if (next) delete next; }

    FooList *functional_append(FooList *) const;
};

And then in my implementation, I define

FooList *FooList::functional_append(FooList *other) const {
    if (this == NULL)
        return other;
    else
        return new FooList(data, next->functional_append(other));
}

Does the condition on the second line make any sense? Will this ever be NULL? I know that if functional_append was declared virtual then this would throw a segmentation fault once this == NULL, but as a simple member function would it still work like I expect it to?


Note: I am looking for a reason why the above will or will not work (like the equivalent C code), not just "No, it can't happen" or "Yes, if force it to like this ...".

randomusername
  • 7,927
  • 23
  • 50

2 Answers2

2

You can do something like

 MyClass* p = NULL;
 p->foo();

and foo() might by actually called, and a test for this == NULL yields true.

Nevertheless the above sample is simply raising undefined behavior, at the point when p is dereferenced. A check for this == NULL to determine any further logical behavior, is beyond all hope.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

Will this ever be NULL?

Yes, this could be NULL. But that would be the case your program is behaving incorrectly ( i.e maybe corrupted memory or something else). Then there would be many more things to check for rather than putting this == NULL.

In normal scenarios this can never be NULL as when you call a function on a valid object then this is implicitly passed by compiler to that function.

ravi
  • 10,994
  • 1
  • 18
  • 36