Example of Explicit Initialization by Constructor


/************************************************************************
*

The following example shows the declaration and use of several constructors that explicitly initialize class objects:

                                                                        *
************************************************************************/

// This example illustrates explicit initialization
// by constructor.

#include <iostream.h>
class complx
{
      double re, im ;
public:
      complx();   // default constructor
      complx(const complx& c) {re = c.re; im = c.im;}
                  // copy constructor
      complx( double r, double i = 0.0) {re = r; im = i;}
                  // constructor with default trailing argument
      void display()
      {
            cout << "re = "<< re << " im = " << im << endl;
      }
};

void main ()
{
      complx one(1);      // initialize with complx(double, double)
      complx two = one;   // initialize with a copy of one
                          // using complx::complx(const complx&)
      complx three = complx(3,4);  // construct complx(3,4)
                                   // directly into three
      complx four;                 // initialize with default constructor
      complx five = 5;             // complx(double, double) & construct
                                   // directly into five
      one.display();
      two.display();
      three.display();
      four.display();
      five.display();
}

/************************************************************************
*

The above example produces the following output:

re = 1 im = 0
re = 1 im = 0
re = 3 im = 4
re = 0 im = 0
re = 5 im = 0

                                                                        *
************************************************************************/