Returning *This

Why would you ever return a *this pointer in a memeber function of a class?

for example:

1
2
3
4
5
6
7
8
9
10
11
Time::Time( int hr, int min, int sec ){
setTime( hr, min, sec );
}

Time &Time::setTime(int h, int m, int s){

setHour(h);
setMinute(m);
setSecond(s);
return *this; //What is it returning??? I know its returning the OBJECT but why?
}


Why is it returning the Object?? And in the constructor "setTime" is called but there are no variables to retrieve the returning value?? so why is it returning *this..

also why does it do this Time &Time::setTime isn't this saying that its going to return a reference even though it doesnt return a reference it returns a pointer.. and can't the code be return as
Time::& setTime??

I know I got alot of questions.
Last edited on
That will allow you to do
1
2
3
4
Time t,u,v,w;
t.setTime(h,m,s).setAnotherThing(a,b,c); // you are modifying the same object 
u = v = w = Time(h,m,s);
u = v.setTime(h,m,s) = w;

this is a pointer to the object, so *this is an object.
However that concatenation of methods can be confusing. In setters I prefer not returning anything (throwing an exception or setting error flags), or return bool
Yes but when its returning the Object.. what does it return to??

Like when the object is returned where does it go???
Last edited on
It returns a reference to the object - that is, an alias to itself.
If you don't "use" it, nothing happens.
I understand, how in Operator overloading you might need to return a *this (or ojbect)

like as in
1
2
3
4
operator&>(const otherclass &otherobject){

return otherobject < *this
}


but in the

1
2
3
4
5
6
7
8
9
10
11
Time::Time( int hr, int min, int sec ){
setTime( hr, min, sec );
}

Time &Time::setTime(int h, int m, int s){

setHour(h);
setMinute(m);
setSecond(s);
return *this; //What is it returning??? I know its returning the OBJECT but why?
}


What is the point of returning the Object?? How does it allow for concading???

Well. Consider:
1
2
3
4
5
6
7
Time someTime(3,13,37);
//Now we call setTime:
someTime.setTime(6,27,14);
//Since setTime returns a reference to the object, the above can be used as an alias to someTime, e.g.
someTime.setTime(6,27,14).setTime(3,13,37).setTime(12,54,28); //not very useful, but possible
//and:
Time someOtherTime=someTime.setTime(6,27,14); //set someTime, then construct someOtherTime from someTime 


Having setTime return a reference to the object is not particularly useful, however it is useful for operator=.
Last edited on
Yes its now very clear to me. Thanks for your help.
........ =.=
hihi
Pardon me for asking..
i tried to read for a few times... i dun even know what eu all are talking abt...
and for Analyzer said its clear ....

I feel so dumb now....
Topic archived. No new replies allowed.