Cascaded function calls

How to define cascaded functions in C++

With this pointer

Every object can access itself through a pointer named this. The this can be used implicitly or explicitly. By returning this pointer in the member function, we can construct cascaded function calls:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Time{
public:
Time &setHour(int h){
hour=h;
return *this;
}
Time &setMinute(int m){
minute=m;
return *this;
}
Time &setSecond(int s){
second=s;
return *this;
}
private:
int hour;
int minute;
int second;
}

NOTE: The return value of all these functions are references, which means we can directly modify the object.

Using the above class definition, we can make the cascaded functions calls:

1
2
Time t;
t.setHour(2).setMinute(30).setSecond(25);

ATTENTION: One more thing about this accessor is that it cannot be used inside a static class member. Because the static class members exist independently of any objects of a class.

With operator(<<, >>) overloading

We can overload the stream extraction operator >> and the stream insertion operator << and, by returning reference to the stream operators, construct the cascaded functions.

1
2
3
4
5
6
7
8
9
10
11
ostream& operator<<(ostream& output, const string test){
output<<"("<<test<<")";
return output; \\return the reference to ostream
}
istream& operator>>(istream& input, string test){
input.ignore();
input.setw(4)>>test; \\ read 4 characters from the istream
input.ignore();
return input; \\return the reference to istream
}

This enables input and output operators to be cascaded as follows:

1
2
cin>>test1>>test2;
cout<<test1<<test2;

By Mingfei

0%