This question already has an answer here:
I was just going through random pages on Cprogramming.com and noticed the Constructors and Destructors tutorial/example page. They have used the following method of defining a constructor:
class String
{
private:
char *str;
int size;
public:
String() : str(NULL), size(0) { } // <- This statement
String(int size) : str(NULL), size(size) { // <- And this one
str = new char[size];
}
}
I've been using the good old fashioned definition of constructors with the magic this
pointer:
String() {
this->str = NULL;
this->size = 0;
}
String(int size) {
this->size = size;
this->str = new char[size];
}
Is there any added benefit in the first declaration beside the obvious smaller code (less number of lines)?
PS: It has been quite a few years since I last did write something in C++.
i was like you, with the back old collage knowledge this usage seems weird. But then understand that by using this technique, custom class implementations give better performance on runtime. And here is a long explanation about initiatization lists from the father of C++.
Those are constructor initialization lists, and for fundamental types there is no difference with respect to the form you are used to, which is based on assignment rather than initialization.
However, for user-defined types there might be a difference in terms of performance (and semantics perhaps) between:
Also, you do not have a choice for those types that are not default-constructible other than using a member initialization list to initialize them, and you do not have a choice for
const
and reference members either, that must be initialized immediately.Constructing objects in C++ is done in three steps:
The constructor definition
String() : str(NULL), size(0) {}
assigns the proper value to the variables in step 2.The constructor definition
String() { this->str = NULL; this->size = 0; }
does this in step 3. Step 2 is, however, executed nevertheless. So this kind of assigning the proper value to the member variables is less efficient.