RAD Studio |  |

Constructor Defaults
See Also
Collapse All

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

Copy Code

    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

Copy Code

    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:

Copy Code

    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;
    }

See Also

Constructors

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!