C++: Constructor

Posted March 1, 2006 by William_Wilson in C programming

This tech recipe explains the implementation of C++’s for many constructors types.

The classic constructor is still available in C++, but they also offer a few additions to allow for shortened code and fewer constructors.

*I will write the following constructors as if they were in a class called Constructor with three global fields to be initialized which include name, size, and text.

Default Constructor:

Constructor() {
name = "";
size = 0;
text = "";

-This takes zero parameters and initializes them as any other language could.

Parameter List Constructor:

Constructor(String n, int s, String t){
name = t;
size = s;
text = t;

-Again, it is similar to other languages, but this kind of work is not necessary. This is one of many places where C++ shines.

Paramenter List Constructor 2:

Constructor(String n, int s, String t):name(n),size(s),text(t) {}

-This method utilizes a feature similar to the constructor. It is as if your primitive types now have their own constructors. Therefore, your code is simplified.

*There is one more thing you can add to this last modification. It will combine the Default and List Parameter Constructors into one.
It will also allow for only partial constructors (e.g., Only enter a name or name and size.)

List Parameter with Defaults Constructor:

Constructor(String n="", int s=0, String t=""):name(n),size(s),text(t) {}

-In this case, when information is supplied and if only one field is given, the left most field is assumed to be the field supplied. If any fields are left out or this constructor is called as the default, the values set equal will be used instead.

Now, all well and good for primitives, but what about objects?
C++ to the rescue! There is a copy constructor format which you can use to initialize an object using another object of the same type.

Copy Constructor:

Constructor(const Constructor& c){
this->name = c.name;
this->size = c.size;
this->text = c.text;

NOTE: The parameter in this constructor needs to be constant AND passed by reference. This assures the C++ compiler that the object this and the parameter object are not the same object. Self assignment is definitely NOT ALLOWED.

*Also, note that the copy constructor requires the use of a default or reasonable equivalent to be written to initialize the this object.

Questions/Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.