Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Default constructors

A default constructor is one that can be called with no arguments. A default constructor is used to create a “vanilla object,” but it’s also very important when the compiler is told to create an object but isn’t given any details. For example, if you take the class Y defined previously and use it in a definition like this,

Y y4[2] = { Y(1) };

the compiler will complain that it cannot find a default constructor. The second object in the array wants to be created with no arguments, and that’s where the compiler looks for a default constructor. In fact, if you simply define an array of Y objects,

Y y5[7];

or an individual object,

Y y;

the compiler will complain because it must have a default constructor to initialize every object in the array. (Remember, if you have a constructor the compiler ensures it is always called, regardless of the situation.)

The default constructor is so important that if (and only if) there are no constructors for a structure ( struct or class), the compiler will automatically create one for you. So this works:

//: C06:AutoDefaultConstructor.cpp
// Automatically-generated default constructor

class V {
  int i;  // private
}; // No constructor

int main() {
  V v, v2[10];
} ///:~

If any constructors are defined, however, and there’s no default constructor, the above object definitions will generate compile-time errors.

You might think that the default constructor should do some intelligent initialization, like setting all the memory for the object to zero. But it doesn’t – that would add extra overhead but be out of the programmer’s control. If you want the memory to be initialized to zero, you must do it yourself.

Although the compiler will create a default constructor for you, the behavior of the automatically-generated constructor is rarely what you want. You should treat this feature as a safety net, but use it sparingly – in general, you should define your constructors explicitly and not allow the compiler to do it for you.

Contents | Prev | Next

CodeGuru - the website for developers.