tags:

views:

495

answers:

15

What is purpose of this keyword. Doesn't the methods in a class have access to other peer members in the same class ? What is the need to call a this to call peer methods inside a class?

+1  A: 

It allows you to get around members being shadowed by method arguments or local variables.

Ignacio Vazquez-Abrams
Could you give an example ??
de costo
It can also help to improve readability if it is unclear what the member variables are i.e. `this->m_var = var`.
Chris
A: 

Sometimes you want to directly have a reference to the current object, in order to pass it along to other methods or to store it for later use.

In addition, method calls always take place against an object. When you call a method within another method in the current object, is is equivalent to writing this->methodName()

You can also use this to access a member rather than a variable or argument name that "hides" it, but it is (IMHO) bad practice to hide a name. For instance:

void C::setX(int x) { this->x = x; }

Uri
+3  A: 

Consider the case when a parameter has the same name as a class member:

void setData(int data){
  this->data = data;
}
Justin Ethier
+11  A: 
  • Helps in disambiguating variables.
  • Pass yourself as a parameter or return yourself as a result

Example:

struct A
{
    void test(int x)
    {
        this->x = x;                 // Disambiguate. Show shadowed variable.
    }
    A& operator=(A const& copy)
    {
        x = copy.x;
        return *this;                // return a reference to self
    }

    bool operator==(A const& rhs) const
    {
         return isEqual(*this, rhs); // Pass yourself as parameter.
                                     // Bad example but you can see what I mean.
    }

    private:
        int x;
};
Martin York
A: 

For clarity, or to resolve ambiguity when a local variable or parameter has the same name as a member variable.

Syntactic
A: 

The this pointer inside a class is a reference to itself. It's needed for example in this case:

class YourClass
{
   private:
      int number;

   public:
      YourClass(int number)
      {
         this->number = number;
      }
}

(while this would have been better done with an initialization list, this serves for demonstration)

In this case you have 2 variables with the same name

  1. The class private "number"
  2. And constructor parameter "number"

Using this->number, you let the compiler know you're assigning to the class-private variable.

LukeN
+2  A: 

It lets you pass the current object to another function:

class Foo;

void FooHandler(Foo *foo);

class Foo
{
    HandleThis()
    {
       FooHandler(this);
    }  
};
Eclipse
+1  A: 

For example if you write an operator=() you must check for self assignment.

class C {
public:
    const C& operator=(const C& rhs)
    {
        if(this==&rhs) // <-- check for self assignment before anything
            return *this;
        // algorithm of assignment here
        return *this; // <- return a reference to yourself
    }
};
Notinlist
+23  A: 

Two main uses:

  1. To pass *this or this as a parameter to other, non-class methods.

    void do_something_to_a_foo(Foo *foo_instance);
    
    
    void Foo::DoSomething()
    {
        do_something_to_a_foo(this);
    }
    
  2. To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
    MessageBox::MessageBox(const string& message)
    {
      this->message = message;
    }
    (Although an initialization list is usually preferable to assignment in this particular example.)
Josh Kelley
+1. There's a third case: If you have a class template with a base class that depends on the template parameters, accessing members of the base class requires `this->` or `baseclass::` to delay name lookup.
sellibitze
Or to check for weird errors with this != NULL
josefx
@josefx: That's one of those comments which make me regret that we cannot down-vote comments.
sbi
@sbi true, I should have added that 1) this != NULL only helps to understand that a member function may get called on an invalid object as foo->bar() is almost the same as bar(foo) 2) it should only be used for debugging and only if anything else already failed, which means almost never.
josefx
@josefx: To me it seems that, besides some corner cases, a `this` pointer would usually be `NULL` in code that uses the classic `delete p; p=NULL;` anti pattern. In other words: in code that _manually fiddles with dynamic memory_ (and gets it wrong, of course). The way to solve such problems is not to put assertions in to catch its classic errors (note: _if at all,_ it should certainly be `assert(this);`). __The solution is to never write such code.__
sbi
+1  A: 

The this pointer is a way to access the current instance of particular object. It can be used for several purposes:

  • as instance identity representation (for example in comparison to other instances)
  • for data members vs. local variables disambiguation
  • to pass the current instance to external objects
  • to cast the current instance to different type
Franci Penov
+3  A: 

The expression *this is commonly used to return the current object from a member function:

return *this;

The this pointer is also used to guard against self-reference:

if (&Object != this) {
// do not execute in cases of self-reference
dlb
(see also http://msdn.microsoft.com/en-us/library/y0dddwwd%28VS.80%29.aspx )
sth
A: 

It also allows you to test for self assignment in assignment operator overloads:

Object & operator=(const Object & rhs) {
  if (&rhs != this) {
    // do assignment
  }
  return *this;
}
Ron Warholic
+3  A: 
  1. Resolve ambgiguity between member variables/functions and those defined at other scopes
  2. Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
  3. Trigger IntelliSense in the IDE (though that may just be me).
JohnMcG
#3 -- I know some people who do that. I can always tell when I'm looking at code they wrote because it is uuuugly (well, for more reasons than just the extraneous `this->` all over the place).
Dan
+2  A: 

Some points to be kept in mind

  • This pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.

  • This pointer is not counted for calculating the size of the object.

  • This pointers are not accessible for static member functions.

  • This pointers are not modifiable

Look at the following example to understand how to use the 'this' pointer explained in this C++ Tutorial.

class this_pointer_example // class for explaining C++ tutorial 
{
    int data1;
 public:
    //Function using this pointer for C++ Tutorial
    int getdata()
    { 
        return this->data1;
    } 
  //Function without using this pointer 
  void setdata(int newval)
  {
       data1 = newval;
  }
};

Thus, a member function can gain the access of data member by either using this pointer or not. Also read this to understand some other basic things about this pointer

piemesons
+1 for mentioning that this isn't available to static methods.
mikek3332002
A: 

It also allows objects to delete themselves. This is used in smart pointers implementation, COM programming and (I think) XPCOM.

The code looks like this (excerpt from some larger code):

class counted_ptr
{
private:
    counted_ptr(const counted_ptr&);
    void operator =(const counted_ptr&);

    raw_ptr_type            _ptr;
    volatile unsigned int   _refcount;
    delete_function         _deleter;
public:

    counted_ptr(raw_ptr_type const ptr, delete_function deleter)
        : _ptr(ptr), _refcount(1), _deleter(deleter) {}
    ~counted_ptr() { (*_deleter)(_ptr); }
    unsigned int addref() { return ++_refcount; }
    unsigned int release()
    {
        unsigned int retval = --_refcount;
        if(0 == retval)
>>>>>>>>        delete this;
        return retval;
    }
    raw_ptr_type get() { return _ptr; }
};
utnapistim