Have you ever heard of the Rule Of Three? If not, then you must read this tutorial. This is how we are going to define it, using plain words:
Well, since we are going to build such a class, we need to cover this. We are going to do that thoroughly! Luckily it is not that hard. Just follow me.
The problem is that we want to make code below work correctly:
Code:
void SomeFunction(const String& s)
{
String B("Okidoky");
B=s;
}
int main()
{
String A = "Hello";
String B(A);
//Or String B = A;
A = A;
SomeFunction(A);
String C = A;
return 0;
}
Class String is internally represented by a pointer. This pointer allocates memory dynamically.
To make the simple code posted above happen, we'll need to develop this custom String class with care. Or better, we need to set up the very basics of this class properly. Here is my global plan on how I am going to teach you to do just that:
Learn the difference between assignment and initialization.
Learn why operator= is a requirement.
Learn why we must implement a copy constructor.
It will be a long walk if you're not familiar with this concept. But in the end it is worth it. After finishing this tutorial, you'll be strengthened alright...
NOTICE: we will implement the destructor without giving it much attention! You should know what a destructor basically does and how to free memory with it.