When Should You Use the "This" Keyword in C++

Is it wise to use the `this` keyword in C?

Using this in any fashion you want is totally valid C.

What you have to ask yourself, by the way these apply to any C++ reserved words like class, final etc, is :

  • Do I use a program that highlights this as a keyword conveing the wrong message ? e.g. Visual Studio highlights this even when you're in a .c file so some confusion may arise.
  • Do I plan to promote my code to C++ in the future ? In such a case you'll have some extra work to do that could be avoided.
  • Does my code interact with C++ ? This is not a problem per se but you have to bear in mind that your code will interact with C++ programmers as well. And you don't won't to confuse people that may not be aware of C in great detail (even though someone may say it's their duty do be aware of what they're doing when reading another language).

Since this is something that can be avoided I find using it immoral but not incorrect.

I'm not saying you have to study C++ prior to writing C, but once you know something, it's a good practice to make good use of it.

A subtle problem you may cause is to make your code 'uncallable' from C++ for example a

#define this some_definition

in a C header file that is later included from C++ may have weird effects to your code.

When should you use the this keyword in C++?

While this is a totally subjective question, I think the general C++ community prefers not to have this->. Its cluttering, and entirely not needed.

Some people use it to differentiate between member variables and parameters. A much more common practice is to just prefix your member variables with something, like a single underscore or an m, or m_, etc.

That is much easier to read, in my opinion. If you need this-> to differentiate between variables, you're doing it wrong. Either change the parameter name (from x to newX) or have a member variable naming convention.

Consistency is preferred, so instead of forcing this-> on yourself for the few cases you need to differentiate (note in initializer lists this is completely well-defined: x(x), where the member x is initialized by the parameter x), just get better variable names.

This leaves the only time I use this: when I actually need the address of the instance, for whatever reason.

Use of this keyword in C++

Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:

Person::Person() {
int age;
this->age = 1;
}

Also, this:

Person::Person(int _age) {
age = _age;
}

It is pretty bad style; if you need an initializer with the same name use this notation:

Person::Person(int age) : age(age) {}

More info here: https://en.cppreference.com/w/cpp/language/initializer_list

When do you use the this keyword?

There are several usages of this keyword in C#.

  1. To qualify members hidden by similar name
  2. To have an object pass itself as a parameter to other methods
  3. To have an object return itself from a method
  4. To declare indexers
  5. To declare extension methods
  6. To pass parameters between constructors
  7. To internally reassign value type (struct) value.
  8. To invoke an extension method on the current instance
  9. To cast itself to another type
  10. To chain constructors defined in the same class

You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.

this keyword, what does this mean?

this is just a pointer to a current object of the class to which the function is a member of. Its more of a hidden parameter that is passed to every NON-STATIC method of a c++ class. It simply points to a specific instance of a class along with all the data that the object has. So for your example:

Token::~Token() {
if(this == nullptr) { return; }
.... }

This is just pointing to the object of the Token classes' destructor function.

if(this == nullptr) { return; }

To be even more specific, the if statement above is seeing if the instance of the object is equal to a null reference.

Implementation restrictions of this keyword in C++, as it relates to dangerous but functional example

So I reached out to Stephan Lavavej (Stephan's website), who maintains the Standard Library implementation for Microsoft, with this question. I will post his answer below. I do want to point out that user HAL9000 was essentially right with his answer, but since Stephan's was so thorough, I'll post it, and eventually designate it as the official answer(it's hard to get more official than the words of someone who actually maintains a Big 3 implementation of the Standard). If you find this answer informative, HAL9000's answer has a visual example to reinforce the idea.

Stephan's Words:

You shouldn't think of the "this" pointer as being stored within an object. The implicit parameter mental model is the most accurate one.
When a function x() calls a member function Meow::y() on a Meow object m, x() has to know the address of m already. It might be a local variable (x() knows where all of its local variables live on the stack), it might be a dereferenced pointer (if m is *ptr, ptr points to m), it might be passed via reference (references are not pointers, but they effectively have the same location information as pointers), it might be an element on an array (if m is arr[idx], then arr + idx points to m), etc. So Meow::y() will be implicitly passed the address of m, which becomes "this" within the member function.

Crucially, if you have a struct that contains plain old data (e.g. a bunch of ints) and you swap the contents of two structs, the objects don't change identity - only their contents. If I take all of your stuff in your house and swap it with the stuff within someone else's house, the locations of the houses are unchanged. (In C++, objects can't migrate from one memory address to another - the most you can do is create a separate object, move all the stuff, tell anyone who cares about the old location to instead point to the new location, and then destroy the empty shell of the original object - that's move semantics, basically.)

Because "this" isn't actually stored anywhere, it has zero cost, which is useful to know. (This is outside virtual member functions, which do make objects pay a vptr cost, but that's much more advanced.)

Hope this helps,
STL

Is there a difference between using 'this' keyword in the constructor of a class or not using it in C++

No need to use 'this' keyword in the constructor unless you have the same name for a class attribute and a parameter.

Gui::Gui(const double organismSize, const double foodSize )
{
organismSize =organismSize; // we have an ambiguity, the compiler cannot make a difference between the parameter and the attribute
foodSize = foodSize ;
}

Gui::Gui(const double organismSize, const double foodSize )
{
this->organismSize =organismSize; // the compiler can make a difference between the parameter and the attribute
//this->organismSize is the attribute while organismSize is the parameter
this->foodSize = foodSize ;
}

What is the purpose of 'this' keyword in C#

There are a couple of cases where it matters:

  • If you have a function parameter and a member variable with the same names, you need to be able to distinguish them:

    class Foo {
    public Foo(int i) { this.i = i; }

    private int i;
    }
  • If you actually need to reference the current object, rather than one of its members. Perhaps you need to pass it to another function:

    class Foo {
    public static DoSomething(Bar b) {...}
    }

    class Bar {
    public Bar() { Foo.DoSomething(this); }
    }

    Of course the same applies if you want to return a reference to the current object

C# When To Use This Keyword

The constructors are the same. The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always use this when referring to instance variables and properties.

I no longer use the this keyword in this way after moving to a different company with different standards. I've gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).

My version of your class:

class Life
{
//Fields
private string person;
private string partner;

//Properties
public string Person
{
get { return this.person; }
set { this.person = value; }
}

public string Partner
{
get { return this.partner; }
set { this.partner = value; }
}

public Life()
{
this.person = "Dave";
this.partner = "Sarah";

MessageBox.Show("Life Constructor Called");
}
}

or, even better, but not as clear about the use of this with fields.

class Life
{

//Properties
public string Person { get; set; }
public string Partner { get; set; }

public Life()
{
this.Person = "Dave";
this.Partner = "Sarah";

MessageBox.Show("Life Constructor Called");
}
}


Related Topics



Leave a reply



Submit