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??
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
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???
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=.
........ =.=
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 ....