FAQ 20.08 What is the default constructor ?

FAQ 20.08 What is the "default constructor"?

It's the constructor that can be called with no arguments.

For a class Fred, the default constructor is often simply Fred::Fred(), since certainly that can be called (and in this case, must be called) with no arguments. However it is possible (and even likely) for a default constructor to take arguments, provided they are given default values.

 class Fred { public:   Fred(int i=3, int j=5) throw();                    <-- 1   // ... }; 

(1) Default constructor: Can be called with no args

In either case, the default constructor is called when an object is created without any initializers. For example, object x is created by calling Fred::Fred(int,int) with defaulted arguments (3,5).

 void sample() throw() {   Fred x;                                            <-- 1   Fred y(3,5);                                       <-- 2   // ... } 

(1) Calls the default constructor

(2) Same effect as with object x

Similarly the default constructor (in this case, including the defaulted parameters) is called for each element of an array. For example, each element of array a and vector b (see FAQ 28.13) is initialized by calling Fred::Fred(int,int) and passing the defaulted arguments (3,5). However, vectors are more powerful than arrays, since vectors can use something other than the default constructor when initializing the array elements (an especially important feature for those classes that don't have a default constructor). For example, the 10 elements of vector c are initialized with Fred(7,9) rather than the default choice of Fred(3,5):

 #include <new> #include <vector> using namespace std; void sample2() throw(bad_alloc) {   Fred a[10];                                        <-- 1   vector<Fred> b(10);                                <-- 2   vector<Fred> c(10, Fred(7,9));                     <-- 3 } 

(1) Arrays use the contained object's default ctor

(2) vector can use the contained object's default ctor

(3) vector doesn't have to use the default ctor

Note that adding an empty pair of parentheses after a declaration is not the same as calling the default constructor. In the following example, x is an object of class Fred, but y is declared to be a function that returns a Fred by value; y is not a Fred object.

 void sample3() throw() {   Fred x;                                            <-- 1   Fred y();                                          <-- 2   // ... } 

(1) Creates an object

(2) Declares a function; does not create a Fred object



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net