This section demonstrates how to provide a default constructor that is not implicitly called. This provides explicit control over when an object is constructed (see also the examples in Sections 3.1 and 3.3). Similar to exceptions, the technique uses a new class, Default, to indicate the desire to use the default constructor.
class Default
{
public:
Default() {};
};
class person
{
private:
char *name;
int age;
person() {error("private implicit default person created");}
public:
const int default_age = 5;
person(Default) {name = "default_name", age = default_age;}
person(char *n, int a) {name = n, age = a;}
};
examples()
{
// person p1;
// compiler error: constructor `person::person()' is private
person p2(Default());
person p3("Judy", 29);
}
This technique is useful in preventing misinterpretations such as that in the following code:
main()
{
person chris();
. . .
}
Even if the default constructor person::person() is public, this code does not call it to create person object chris. Instead it declares chris to be a function of zero arguments that returns an object of class person. This confusion can be avoided by using the explicit default technique.