Thursday, November 25, 2010

Default Constructors for Built-in Types

The following compiles: int i = int();

'int()' is "sort of" a default constructor for int which initializes 'i' to zero.

The following are other ways of initializing i to zero.

  int i = 0;
  int i(0);
  static int i; // Also changes the storage class.
  int i; // global, unnamed, or other namespace.

Built-in types do not have default constructors. They do have some syntax that initizializes a built-in typed variable to '0' converted to that type.
For example:
    float f = float();
The above is equivalent to float f = static_cast<float>(0);.

Sometimes, in templates, you will see declarations as follows: T element = T();
This is to catch the case when a built-in type is passed as the template argument for the template parameter T. If you left the "= T()" off, the default constructor would be called for all types except the built-in types.

References:
Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers. Addison-Wesley, 2001.
C++ Templates by David Vandevoorde and Nicolai M. Josuttis. Addison-Wesley, 2003
http://www.gotw.ca

No comments:

Post a Comment