3

So i'm aware that this is a reference to the class itself, however I can't really tell what it does in an if statement

What does the following code do?

    if(this)
    {
       //Code goes here...
    }

I'm fairly sure it is checking if the class is not null, but a further explanation would be great!

Reuben Ward
  • 101
  • 1
  • 9

3 Answers3

1

this pointer is a constant pointer that holds the memory address of the current object. So, technically this will check whether it is null or not which will not be null in member function. Since you will not be able to call a class until you have its object and in abstract classes you can't use this anyway. So, this if doesn't make much sense.

Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37
  • "this will never be null in a member function so the check you perform is useless." This is the same thing so as to what I meant. – Priyansh Goel Apr 13 '16 at 02:55
  • I am taking my downvote away but still your statement is wrong: "which will not be null in member function". `this` can be NULL. – iammilind Apr 13 '16 at 02:58
  • How this can be null? Until and unless your object is there, this can't be used. Am I missing something? – Priyansh Goel Apr 13 '16 at 05:24
0

It's attempting to check to see if the method was called on a NULL pointer, e.g. something like this:

Foo * foo = NULL;
foo->TheMethod();

However, that isn't a valid technique, since calling a method (even a non-virtual method!) on a NULL pointer is undefined behavior and so the test won't work reliably.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
0

It is indeed checking if this != nullptr. However by the time you reach this statement, you have already passed from undefined behavior. Because this is available only in a class method and calling such method with nullptr is UB.

Hence such statement never serves any valid purpose.

Besides UB, also remember that such checks are useful only when called with a pointer. They are irrelevant for object/reference. If the method is virtual then most of the architecture would crash the code before reaching that if.

iammilind
  • 68,093
  • 33
  • 169
  • 336