Open In App

How to create a custom String class in C++ with basic functionalities

Last Updated : 01 Feb, 2022
Comments
Improve
Suggest changes
10 Likes
Like
Report

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: 
 

  1. Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character.
  2. 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.
  3. 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).
  4. 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:
 


Output: 
The string passed is: Hello
The string passed is: Hello

 

Some more functionalities of string class: 
 

  1. pop_back(): Removes the last element from the Mystring object.
  2. push_back(char ch): Accepts a character as an argument and adds it to the end of the Mystring object.
  3. length(): Returns the length of the mystring.
  4. copy(): It copies the mystring object to a character array from a given position(pos) and a specific length(len).
  5. swap(): It swaps the two Mystring objects.
  6. Concatenate two strings using overloading the '+' operator: Allows us to concatenate two strings.


Below is the program to illustrate the above-discussed functionality:
 


Output: 
Mystring b: Hell
Mystring b: Hello
Length of Mystring b: Hello
arr is: Hel
Hello Hello
string d: HelloHello

 

Next Article

Similar Reads