5.3 Parametrized constructors

A constructor can be parametrized. Let us observe the following example:

class Value
{
    int v;
  public:
    Value(void);
    Value(int x);
};

Value::Value(void)
{
  v = 0;
}

Value::Value(int x)
{
  v = x;
}

In this example, we have to constructors in the class Value. The first one has no parameter, which initializes data member v to 0. The other one uses the parameter to initialize data member v. The following is an example of how to use the parametrized constructor:

Value v1(50), v2(10), v3;

In this example, v1 is initialized to 50, v2 is initialized to 10, and v3 is initialized to 0 by the constructor with no parameters.



Copyright © 2006-09-26 by Tak Auyeung