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?
views:
495answers:
15It allows you to get around members being shadowed by method arguments or local variables.
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; }
Consider the case when a parameter has the same name as a class member:
void setData(int data){
this->data = data;
}
- 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;
};
For clarity, or to resolve ambiguity when a local variable or parameter has the same name as a member variable.
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
- The class private "number"
- And constructor parameter "number"
Using this->number
, you let the compiler know you're assigning to the class-private variable.
It lets you pass the current object to another function:
class Foo;
void FooHandler(Foo *foo);
class Foo
{
HandleThis()
{
FooHandler(this);
}
};
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
}
};
Two main uses:
To pass
*this
orthis
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); }
- To allow you to remove ambiguities between member variables and function parameters. This is common in constructors.
(Although an initialization list is usually preferable to assignment in this particular example.)MessageBox::MessageBox(const string& message) { this->message = message; }
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
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
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;
}
- Resolve ambgiguity between member variables/functions and those defined at other scopes
- Make explicit to a reader of the code that a member function is being called or a member variable is being referenced.
- Trigger IntelliSense in the IDE (though that may just be me).
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
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; }
};