2012年1月19日 星期四

Default Constructor


The Default Constructor

A default constructor is the constructor that is executed when no arguments are provided in the declaration. There are three possible situations for

this:

1. If you do not provide any constructor for a class, the compiler-provided one is considered the default constructor. It, of course, does not do anything other than allocating memory for the class object.

This looks like:

class x
{
…        // no constructors defined for the class
};

2. If you provide a constructor without any arguments (void), then that is the class default constructor.

This looks like:

class x
{

  x();    // or x(void);   

};

3. If you provide a constructor with all default arguments, then, that, too, may be considered the default constructor. Warning: you may not have a class with both a void-argument constructor and one with all default arguments.

This looks like:

class x
{

  x(int x=5);        // Note:  the only argument is a default argument

};

or maybe like this:

class x
{

  x(double d = 0.0, unsigned short s=0);            // Two default arguments

};

Instantiation of an Object Using the Default Constructor

Objects are declared using the default constructor without parentheses, not even empty parentheses.

For example, to declare (instantiate an object) using any one of the x classes from the previous page, you would write it as:

x object;

or

…    new x;

or

…    new x();

not

x object();


Why can't you declare a class object with parentheses using the default constructor?

Answer:

Suppose you write a function like this:

void funk()
{

    x object();

}

The problem is that the statement, x object();, can take on two meanings. It looks just like a function prototype (a function called object with a

void argument and an x return) and now you want to use it to instantiate an x object? I don't think so. You compiler refuses to be confused.

Instantiation of an Object Using the Default Constructor

Objects are declared using the default constructor without parentheses, not even empty parentheses.

For example, to declare (instantiate an object) using any one of the x classes from the previous page, you would write it as:

x object;

or

…    new x;

or

…    new x();

not

x object();


Why can't you declare a class object with parentheses using the default constructor?

Answer:

Suppose you write a function like this:

void funk()
{

    x object();

}

The problem is that the statement, x object();, can take on two meanings. It looks just like a function prototype (a function called object with a void argument and an x return) and now you want to use it to instantiate an x object? I don't think so. You compiler refuses to be confused.

A default constructor 被執行是當在 declaration 中沒有 arguments 提供.

沒有留言:

張貼留言