RAD Studio
ContentsIndex
PreviousUpNext
Constructor Defaults

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
{
public:
   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; 
}
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!