Search code examples
javac++thiscocos2d-x

Importance of "this"


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?


Solution

  • 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!