If you find this article contains errors or problems rendering it unreadable (missing images or files, mangled code, improper text formatting, etc) please contact the editor so corrections can be made. Thank you for helping us improve this resource
The majority of us should be aware of operators in the language by now. They are the core of most languages and allow you to carry out almost every instruction. The most common operators are the
arithmetic and assignment operators (*,/,+,-,%,=). If any of you are familiar with other programming languages like BASIC or Pascal/Delphi then it might have come to your notice that a character
string (char string[...]) does not give you the option of adding two together quite as easily as in the other languages (ie string = str1 + str2). So what we will be doing today is looking into how a
functional string class can be created that allows for some versitility between data types, all while learning about operator overloading.
So there is my template for the new string structure. I decided to go with a struct because by using typedef around my structure I can then treat it like a data type
rather than a class. Really, it is entirely possible to use a class, but this also demonstrates that you can drop a structure or class into the same situation and it will still work exactly the same.
Also, as it might be apparent, I like to name using a ds at the start to indicate "Dwarfsoft" (so that I do not start clashing with Microsofts String classes) and I use _t to signify that it is a
type rather than just a structure or class. I am including string.h for obvious reasons, but I am also including stdio.h because I like memcpy a lot more than strcpy.
Now on to the operators. The first, and possibly the most useful operator, is the assignment "=" operator. Operators in structures and classes are used in a similar way
to functions with the addition of the "operator" keyword. Let us have a look at a sample assignment overload.
So we can see that the calling function is just a little bit different than what we have been used to in the past. So let us disect. "struct
"code">s_dsString&" is our return type. The return type of an assignment "=" (or for that matter, almost ANY operator overloading) should be a reference to the class or structure that is
being assigned to. "operator=()" is the function name that we are using and "const char
"code">*s" is the parameter that is being passed. With this function we are then able to use our struct in the following way.
dsString_t Name = "Chris Bennett";
In this string type I am also hoping to show you the caution needed to be taken to ensure that errors are checked for. When manipulating memory you should always remember to free up what is no
longer needed (or else memory leaks will occur).