How to create a custom String class in C++ with basic functionalities
In this article, we will create our custom string class which will have the same functionality as the existing string class.
The string class has the following basic functionalities:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character.
- Constructor with only one argument : It accepts a pointer to a character or we can say if we pass an array of characters, accepts the pointer to the first character in the array then the constructor of the String class allocates the storage on the heap memory of the same size as of the passed array and copies the contents of the array to that allocated memory in heap. It copies the contents using the strcpy() function declared in cstring library.
Before doing the above operation it checks that if the argument passed is a NULL pointer then it behaves as a constructor with no arguments.
- Copy Constructor: It is called when any object created of the same type from an already created object then it performs a deep copy. It allocates new space on the heap for the object that is to be created and copies the contents of the passed object(that is passed as a reference).
- Move Constructor: It is typically called when an object is initialized(by direct-initialization or copy-initialization) from rvalue of the same type. It accepts a reference to an rvalue of an object of the type of custom string class.
Below is the implementation of the above methods using custom string class Mystring:
The string passed is: Hello The string passed is: Hello
Some more functionalities of string class:
- pop_back(): Removes the last element from the Mystring object.
- push_back(char ch): Accepts a character as an argument and adds it to the end of the Mystring object.
- length(): Returns the length of the mystring.
- copy(): It copies the mystring object to a character array from a given position(pos) and a specific length(len).
- swap(): It swaps the two Mystring objects.
- Concatenate two strings using overloading the ‘+’ operator: Allows us to concatenate two strings.
Below is the program to illustrate the above-discussed functionality:
Mystring b: Hell Mystring b: Hello Length of Mystring b: Hello arr is: Hel Hello Hello string d: HelloHello