MFC Programmer's SourceBook : Thinking in C++
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 Y 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:

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

Z z, z2[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. This would mean, for example, that if you compiled C code under C++, the effect would be different. If you want the memory to be initialized to zero, you must do it yourself.

The automatic creation of default constructors was not simply a feature to make life easier for new C++ programmers. It’s virtually required to aid backward compatibility with existing C code, which is a critical issue in C++. In C, it’s not uncommon to create an array of structs. Without the default constructor, this would cause a compile-time error in C++.

If you had to modify your C code to recompile it under C++ just because of stylistic issues, you might not bother. When you move C code to C++, you will almost always have new compile-time error messages, but those errors are because of genuine bad C code that the C++ compiler can detect because of its stronger rules. In fact, a good way to find obscure errors in a C program is to run it through a C++ compiler.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru