Hi guys! 😊 We have already made the Dynamic Array class for the integers (See Dynamic Array Class for Int) but now let's make Dynamic Array class for the characters. Luckily, there's a ready-made class called String in C++ that works as Dynamic array for chars. It is available in <string> library.
However, if you want to make your own string class (probably for fun but most probably for it is an assignment 😜) then I'll show you how to do it.
However, if you want to make your own string class (probably for fun but most probably for it is an assignment 😜) then I'll show you how to do it.
Pre-Requisites:
- Familiar with Dynamic allocation.
- Know how to make a Class.
Code:
The private section of this class with contain a dynamic array and the size of the array.
class myString
{
private:
char* str;
int len; //length
public:
//functions here
};
I'm only gonna make the default constructor for this class because the original string class also has no parameterized constructor. And I'm sure you know how to make a default constructor.
Another important constructor that I did not introduce earlier is the Copy Constructor.
What is a Copy Constructor?
A copy constructor a very much likely an assignment operator except for the thing that it is called when you initialize the object of that class type e.g.
myString obj("Hello");
Now our copy constructor will initialize our obj to a string that contains "Hello" so basically it is a lot like a parameterized constructor except the thing that we're not sending it all the parameters i.e. size. Just like the constructors, it is called only when the object is created. In its code, it is the same as the assignment operator except for the fact that it doesn't have the check for the length that whether it's already empty array or not. Now let's write the code for it!
//public section
myString(char* obj)
{
length = strlen(obj); //using default function to get the size of the inputted data
str = new char[length+1];
strcpy( str, obj); //strcpy is the default function for copying of the character arrays
//it copies the object on the right into the object on the left
}
You can make another copy constructor whose input is the string and not char*.
Next on, you can make the assignment operator which does the deep copy and if you don't know how to then please refer to Assignment Operator in C++. Make sure to delete any pre-filled array before you copy.
Another operator that you can make is the subscript operator [ ]. Here's the code:
char & operator [] (int i)
{
return str[i];
}
Try to make the ==, != and + operator too. I'll show you how to make these in the next post. But I'm sure you can make it on your own. :)
Thank you for reading! Best of luck for the assignment! 😝
0 comments:
Post a Comment