Techno World Inc - The Best Technical Encyclopedia Online!

THE TECHNO CLUB [ TECHNOWORLDINC.COM ] => C/C++/C# => Topic started by: Taruna on December 27, 2006, 12:49:18 AM



Title: C++: Constructor
Post by: Taruna on December 27, 2006, 12:49:18 AM
The implementation of C++'s 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 3 global fields to be initialized name, size, and text.

Default Constructor:

Code:
Constructor() { 
     name = "";
     size = 0;
     text = "";
}

-takes 0 parameters, and initializes them as any other language could.

Parameter List Constructor:

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

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

Paramenter List Constructor 2:

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

-this method utilizes a feature similar to the contructor, it is as if your primitive types now have there own constructors!! Simplifying your code.

*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 (eg: only enter a name or name and size only!)

List Parameter with Defaults Constructor:

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

-in this case when information is supplied, 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 that is all well and good for primatives, but what about objects?
C++ to the rescue, there is a copy constructor format wich you can use to initialize an object using another object of the same type!

Copy Constructor:

Code:
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 definately NOT ALLOWED!

*Do also NOTE that the copy constuctor requires the use of a default or resonable equivilant to be written to initialize the this object.