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++.
The Copy constructor is easier to use when our class contains a complex object with several parameters. Whenever we want to add any field to our class, then we can do so just by changing the input to the constructor. One of the most crucial importance of copy constructors is that there is no need for any typecasting.
Among different types of constructors, the copy constructor is the type that uses another object within the same class to initialize the data members of the class within the class. In other words, it creates a copy of an existing object of the class.
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to − Initialize one object from another of the same type. Copy an object to pass it as an argument to a function.
You might want to implement some of the methods of the class using a copy constructor, but not to expose it outside of the class. So then you make it private. Like any other method.
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.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With