Sign in to follow this  

[.net] This?

Recommended Posts

Kincaid    100
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
egwenejs    125
this is a pointer to class object. For example:

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

Foo(int a);

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
CraZeE    217
'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
int value;

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
iMalc    2466
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this