Importance of "this"
Asked Answered
P

6

5

i'm programming in c++ using cocos2dx and when adding a sprite or objects,

this-> addChild(something) and addChild(something)

works. Both ways come up with same result.

But not only in c++, this is used in android programming too (perhaps, all programming languages use "this"?). I've used this in Java to replace ClassName.class, with simple this. But besides this purpose this is used in many ways.

But because I haven't gone deep into programming languages, I don't know if they really do the same job (this-> addChild vs. addChild AND ClassName.class vs. this).

Why do we need this?

.

.

Self Answer:

this is a keyword that refers to the current class instance or object in many object-oriented programming languages.

so...just for comfort?

Protoplasm answered 5/3, 2014 at 4:33 Comment(0)
H
7

this has a few uses. First, in some cases, you will need to explicitly refer to the receiver object in the current method, perhaps if you're passing it as a parameter to another function. For example, consider this C++ code:

void someOtherFunction(SomeClass* arg);

void SomeClass::doSomething() {
    someOtherFunction(this);
}

Here, someOtherFunction is a free function that takes a pointer to a SomeClass object. The only way to call it in the context of doSomething so that the receiver object is the parameter is to use this.

this in C++ is also used in assignment operators, which need to return a reference to the receiver object:

MyClass& MyClass::operator= (MyClass rhs) {
    // Do something to the receiver object
    return *this;
}

Here, return *this; means "return a reference to the receiver object," which couldn't be expressed without this.

this is also used to disambiguate in a few circumstances. For example:

public class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }
}

Here, the use of this in the MyClass constructor is to differentiate between the parameter value and the field value. Referring to value by itself selects the parameter, while using this.value refers to the field.

Hope this helps!

House answered 5/3, 2014 at 4:38 Comment(1)
second example is really new to me. Thank you for the answer.Protoplasm
N
3

consider also a normal type of constructor or setter

public ConstrcutMe (String name, int age)
{
    this.name = name;
    this.age = age;
}

public void setName (String name) {
{
   this.name = name;
}

I believe this fully illustrate why we need this

Nitride answered 5/3, 2014 at 4:39 Comment(1)
Actually it doesn't show why you need this - generally, although it shows this being useful in Java. A language could simply forbid shadowing (why not?) or use a different syntax to assign to member variables (like Ruby does). The only "universal" case I can argue for this is when explicitly needing to refer to the current instance, such as when using in an external method call.Envisage
T
2

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

Usage in Java:

Here is given the 6 usage of this keyword.

  1. this keyword can be used to refer current class instance variable.

  2. this() can be used to invoke current class constructor.

  3. this keyword can be used to invoke current class method (implicitly)

  4. this can be passed as an argument in the method call.

  5. this can be passed as argument in the constructor call.

  6. this keyword can also be used to return the current class instance.

Let's consider a problem:

class student
{  
    int id;  
    String name;  

    student(int id,String name)
    {  
        id = id;  
        name = name;  
    }  
    void display()
    {
        System.out.println(id+" "+name);
    }  
    public static void main(String args[])
    {  
        student s1 = new student(1,"NameA");  
        student s2 = new student(2,"NameB");  
        s1.display();  
        s2.display();  
    }  
}  

Output will be:

0 null
0 null

Solution for the problem:

class Student
{  
    int id;  
    String name;  
    student(int id,String name)
    {  
        this.id = id;  
        this.name = name;  
    }  
    void display()
    {
        System.out.println(id+" "+name);
    }  
    public static void main(String args[])
    {  
        Student s1 = new Student(1,"NameA");  
        Student s2 = new Student(2,"NameB");  
        s1.display();  
        s2.display();  
    }  
}  

Output will be:

1 NameA
2 NameB
Tape answered 5/3, 2014 at 4:36 Comment(0)
R
2

In C++, this is a keyword which evaluates to a pointer to the object the method is being called on.

Strictly for convenience, the compiler can figure out, in some cases, where you want to call another method on the same object. If the object has a fooBar method, then you can write it as this->fooBar();, or for convenience you can write just fooBar(); and the compiler will understand it as this->fooBar();.

However, in other cases you really do need to use this explicitly. Consider if you want the method to return the instance itself. You have to refer to the instance itself somehow, which you can do using return this;. Or, if you want to call another function, say barMan, passing in the instance itself - again you need to use this: barMan(this);.

Resting answered 5/3, 2014 at 4:36 Comment(1)
Why? Some idiot ;) Your reply is perfectly correct. As you already know :)Superscription
E
1

The this keyword (or an equivalent such as self in Python) is a mechanism to "refer to the instance upon which the executing method has been invoked", although the meaning can var across languages and contexts. This - hah! - is thus trivially handy when needing to "pass the current instance" from within a given method.

In addition, some languages require that this (or other expression which evaluates to an instance) is manually specified when invoking a member; that is, this must always be specified: this.m(). Other languages allow an "implicit receiver" meaning that this.m() and m() are equivalent, where m is a member function associated with the current instance.

Likewise, the use of Type.m() usually denotes a call to a "static method" defined on a type; once again, this is language-specific, and some languages support first-class type values, in which no method is truly "static".

There is no particular rhyme or reason other than it is how a particular language has been defined - and questions should be focused on a specific context in a specific language1. For most every reason I can give for one language, I can give a counter-example in a different "OOP" language.


1 Case in point: you refer to ClassName.class, however, in Java this is just special syntax to obtain the corresponding Class object and has nothing to do with this or members (static or not).

Envisage answered 5/3, 2014 at 4:35 Comment(0)
G
1

The this keyword, as you correctly stated, is used to refer to the current instance of a given class.

It's very common to see the this keyword in object-oriented languages like C++ and Java (which is used for Android development), as it can make code easier to read and more uniform. Non-object oriented languages tend not to have it, although I'm sure you could find one that does.

My favorite example is constructors and instance variables. If you a class Ducky and a instance variable String duckName, it makes sense for the constructor to look something like this:

public Ducky(String duckName)
{
  this.duckName = duckName;
}

This way, you can use clear variable names in more than one context without confusing yourself and/or future maintainers of your code.

Galvan answered 5/3, 2014 at 4:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.