When is 'this' required?

Is a pointer required this? I think you will need it if you functionally passed through an instance of the class that it points to this. But in terms of setting / receiving / calling / any members, thisalways optional?

I noted this C ++ because the language that I am particularly interested in, but if someone can confirm that the construction is the same for Java and other OO languages ​​that use a pointer this, would be appreciated.

+5
source share
3 answers

You need this if you have a local variable that has the same name as the member variable. In this case, the local variable is called the shadow member variable. To go to the member variable in this situation, you should use this.

Some people find it good practice to explicitly state that the variable you are changing is a member variable with help thisall the time, but this is not always the case.

+8
source

There are three cases that I can think of:

If you just want to pass a pointer to the current class:

class B;
struct A {
    B* parent_;
    A(B* parent) : parent_(parent) {}
};

struct B {
    A* a;
    B() : a(new A(this)) {}
}; 

In a constructor or member function, where an element is obscured by an argument:

struct A {
    int a;
    void set_a(int a) { this->a = a; }
};

Here, the member variable "a" is obscured by the argument "a", therefore it is this->used to access the element instead of the argument.

( , , )


template <class T>
struct A {
    int a;
};

template <class T>
struct B : public A<T> {
    int f() { return this->a; }
}

a , B B, T. this-> this, this , a , f().

return A::a return this->a, , , this-> . - - , , .

+11

sometimes this is required, perhaps when you pass your object to another function. look at this C # code (for opening a modal form with this parent)

Form1 f = new Form();
f.ShowDialog(this);
-1
source

All Articles