Back to: C++
Chaining is a method that improves the readability of code and can remove repetitions. It was first used in a language called Smalltalk.
multiple << for output
Take a look at this code:
std::cout << "My name is ";
std::cout << name;
std::cout << " and I am ";
std::cout << age;
std::cout << " years old.";
In this code I have used multiple couts to string together literal strings and variables. This will work but there is a better way!
Take a look at this code:
std::cout << "My name is " << name << " and I am " << age << " years old";
This is much easier to read and is an example of how chaining can make code more readable. The code has also removed four lots of std::cout!
When there are multiple things that we wish to output, we can use the << operators to chain them together.