fp_unit:
The following pages are related to the Rule of Three.
Page 11:
The Rule of Three
Have you ever heard of the Rule Of Three? If not, then you MUST read this mini-tutorial. This is how we are going to define it, using plain words as promised in the preface:
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;
} To make this happen, we will need to develop our custom String class with care. Or better, we need to set up the basics of our 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 initialisation.
- Learn why operator= is a must.
- 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. Although this mini-tutorial-in-big-tutorial is off-topic, the whole purpose of this huge tutorial is to strengthen the student in his quest for building up a decent skill set. After finishing this mini-tutorial, you'll be strengthened alright...
Let's start.