what is -> used for

Can somebody explain to me what the following line of code:
"this->numberOfLines = numberOfLines;" means and how can I write it in any other way so it does the same thing?
its for pointers. 'this' is a pointer to the current object used inside class methods.

-> is a lot like the "." operator; down in main you might have
someclass x;
x.getnumlines();

If you instead had someclass *x; you need x->getnumlines() which is shorthand for x[0].getnumlines() or *x.getnumlines() both of which are a little clunky.

the way to write it without the this is to not have a local parameter and a class member of the same name. I am assuming that you have something like

class foo
{
int numlines;
void setnumline(int numlines) //same name as class member...
{
this->numlines = numlines; //the class member is assigned the local parameter value here. this-> is required.
}

void set2(int numlinez) //subtle name change
{numlines = numlinez;} //no this ->

}
Last edited on
I still don't get it
That's ok. Its a little odd.

See this class member function?

void setnumline(int numlines) //same name as class member...
{
this->numlines = numlines; //the class member is assigned the local parameter value here. this-> is required.
}


if you wrote this code:

void setnumline(int numlines) //same name as class member...
{
numlines = numlines;
}

you just did absolutely nothing, right? you just assigned the local parameter to itself, ... the value is unchanged. The compiler cannot understand that you meant the class member because of the way c++ handles variable scope. It looks at the local scope, finds an acceptable answer, and it stops looking!

the ONLY way to tell it to set the class member to the value is to use the this-> which forces the compiler to look at the class level scope instead of locally.

the solution is to NOT name parameters the SAME EXACT NAME as the class member item. Then you can just write the code normally, as both names are resolved correctly (there is no conflicting local version of the class member, so it looks up a level and bingo, it finds it at the class scope level!).

there are other times you need the this-> ... it is not always avoidable, but this scenario, it is avoidable.
Last edited on
okay, I think it's becoming a little more clear. Thank you!
Topic archived. No new replies allowed.