0

Recently I encountered a class that had most member functions with a first line of

if (this == NULL)
  return;

Since this is just passed as an implicit parameter to member functions, this doesn't seem to be undefined behavior. Some might even say it removes a burden on the client by removing the need to check for NULL whenever the client calls the function, but it's the first time I've ever seen such a check.

Is it undefined behavior to call a member function through a NULL pointer, so this check is required to be moved outside the member function?

masrtis
  • 1,282
  • 17
  • 32
  • 1
    Yes, UB. (Consider what would happen if you called a virtual function, for instance.) – Oliver Charlesworth May 17 '14 at 14:35
  • 1
    http://stackoverflow.com/questions/7130878/at-what-point-does-dereferencing-the-null-pointer-become-undefined-behavior?rq=1 might also be of interest. – Mat May 17 '14 at 14:38
  • @OliCharlesworth, would you plz describe a little – Rakib May 17 '14 at 16:50
  • @RakibulHasan Virtual functions are usually implemented by giving the class a pointer to a table of function pointers that are initialized to the proper member functions during the constructor. I think this is what's being referred to by Oli's comment. See http://stackoverflow.com/q/4352032/1181561 – masrtis May 17 '14 at 17:23
  • @masrtis, I know about vtable. Just was confused how this can be a problem here. At runtime the actual type is identified and correct overridden method is called on that object. So if this can create problem for virtual method, why not same for normal method? – Rakib May 18 '14 at 04:44

0 Answers0