27E. More on Constructors


Multiple constructors

A structure type definition can include more than one constructor, as long as no two constructors have the same number and types of parameters. For example, an alternative definition of type Cell with three constructors is as follows.

  struct Cell
  {
    int         item;
    const char* name;

    Cell(int it, const char* nm)
    {
      item = it;
      name = nm;
    }

    Cell(int it)
    {
      item = it;
      name = "";
    }

    Cell()
    {
      item = 0;
      name = "";
    }
  };

The constructor requirement

If you define at least one constructor then each time you create a structured value of that type you must use one of the constructors. For example,
  Cell a(16, "kangaroo");
  Cell b(3);
uses the constructor with two parameters to create a and the constructor with one parameter to create b.

Parameterless constructors

C++ has an unusual rule. To use a parameterless constructor, do not write ( ). For example,

  Cell c;
creates a variable c of type Cell and initializes it using the constructor with no parameters. Similarly,
  Cell* p = new Cell;
creates a new Cell in the heap and initializes that cell using the parameterless constructor.

Watch out

In C++, statement
  Cell d();
does not create a Cell at all. It is interpreted as a function prototype for a function called d that takes no parameters and returns a value of type Cell.


Exercises

  1. Define type Complex, where a value of type Complex contains two values of type double called rePart and imPart. Define two constructors: one takes two parameters of type double and installs them into rePart and imPart; the other takes no parameters and sets both fields to 0.0. Answer

  2. Using type Complex from the preceding exercise, write a statement that creates a new complex number whose rePart field is 1.0 and whose imPart is 2.5. Call the new complex number z, and put it in the frame for the current function. Answer

  3. Repeat the previous exercise, but this time allocate the complex number in the heap, and make z a pointer to it. Answer

  4. Write a statement that creates variable zero of type Complex. Initialize it using the parameterless constructor. Answer