• Advertisement
Sign in to follow this  

[.net] This?

This topic is 4644 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I feel a little stupid posting this here, but I can't seem to find out what the "this" statement does in c++; Can anyone tell me ?? Thanx in advance

Share this post


Link to post
Share on other sites
Advertisement
this is a pointer to the instance of the class it's used in.

EDIT: Also, what does this have to do with .NET?

Share this post


Link to post
Share on other sites
this is a pointer to class object. For example:

Class Foo {
int a;
int b;
int c;

Foo(int a);
~Foo();
}

Foo::Foo(int a) {
this->a = 0;
this->b = a;
this->c = this->a;
}

The Foo constructor initializes its members a to 0, b to the value passed to it and c to 0. Hope the above helps.

Share this post


Link to post
Share on other sites
'this' is a language keyword that resolves to the pointer of the current object. It is espeecially useful when resolving variables that have name collisions. Example:


class Foo
{
private:
int value;

public:
void ChangeValue( int value );
};

void Foo::Changevalue( int value )
{
//value = value; <-- Which 'value' is assigned to which?
// In the above, the function local scope takes precedence. So you're
// only manipulating (pointlessly) the function parameter.

this->value = value;
// By using the 'this' reference, you specifically resolve to use the
// class member and assign it the value of the incoming parameter.
}



Note however that the above example *SHOULD* not happen in real scenarios because variable names should be decided carefully to avoid ambiguous clashes.

Share this post


Link to post
Share on other sites
Using this-> is pretty much redundant, unless you're using it to resolve ambiguities. Although I think that resolving ambiguities is done better by using different variable names to the class member names. e.g. appending m_ to the member variable name.

However using *this is often very useful. e.g.
	inline bool operator > (const ubigint& q) const
{ return q < *this; }
In fact I don't think there is any other way to do what that does.

Oh, and if you've ever used Pascal or Delphi, it's the same thing as self.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement