© Will Briggs 2019Will BriggsC++ for Lazy Programmershttps://doi.org/10.1007/978-1-4842-5187-4_17
Lynchburg, VA, USA
You may have seen this error:
char string1 = "Hello", string2 = "Hello";
if (string1 == string2) ...
This condition fails because == for arrays compares memory addresses, not contents, and the addresses differ.
This also causes problems:
It copies not string2’s contents, but its address, to string1. string1’s contents are lost. This is wasteful and also error-prone:
string2 = 'a'; //string1 becomes "Hallo", though it
//wasn't even mentioned here!
So let’s make our own string class, forcing the operators to do what we want, and never worry about this again. ...