Constructor Defaults

From Appmethod Topics
Jump to: navigation, search

Go Up to Constructors Index

The default constructor for class X is one that takes no arguments; it usually has the form X::X(). If no user-defined constructors exist for a class, the compiler generates a default constructor. On a declaration such as X x, the default constructor creates the object x.

Like all functions, constructors can have default arguments. For example, the constructor

X::X(int, int = 0)

can take one or two arguments. When presented with one argument, the missing second argument is assumed to be a zero int. Similarly, the constructor

X::X(int = 5, int = 6)

could take two, one, or no arguments, with appropriate defaults. However, the default constructor X::X() takes no arguments and must not be confused with, say, X::X(int = 0), which can be called with no arguments as a default constructor, or can take an argument.

You should avoid ambiguity in defining constructors. In the following case, the two default constructors are ambiguous:

class X
   X(int i = 0);
int main()
   X one(10);  // OK; uses X::X(int)
   X two;      // Error;ambiguous whether to call X::X() or
               // X::X(int = 0)
   return 0;

See Also