Wrox Press C++ Tutorial


Arrays of Objects of a Class

We can declare an array of objects of a class in exactly the same way that we have declared an ordinary array, where the elements were one of the built-in types. Each element of an array of class objects causes the default constructor to be called.

Try It Out - Arrays of Class Objects

We can use the class definition of Box from the last example, but modified to include a specific default constructor:

// Ex6_10.cpp
// Using an array of class objects
#include <iostream>
using namespace std;

class Box               // Class definition at global scope
{
   public:
      // Constructor definition
      Box(double lv, double bv=1.0, double hv=1.0)
      {
         cout << endl << "Constructor called.";
         length = lv;                        // Set values of
         breadth = bv;                       // data members
         height = hv;
      }

      Box()                          // Default constructor
      {
         cout << endl
              << "Default constructor called.";
         length = breadth = height = 1.0;
      }

      // Function to calculate the volume of a box
      double Volume()
      {
         return length * breadth * height;
      }

   private:
      double length;               // Length of a box in inches
      double breadth;              // Breadth of a box in inches
      double height;               // Height of a box in inches
};

int main(void)
{
   Box Boxes[5];              // Array of Box objects declared
   Box Cigar(8.0, 5.0,1.0);   // Declare Cigar box

   cout << endl
        << "Volume of Boxes[3] = " << Boxes[3].Volume()
        << endl
        << "Volume of Cigar = " << Cigar.Volume();
   cout << endl;

   return 0;
}

How It Works

We have modified the constructor accepting arguments so that only two default values are supplied, and we have added a default constructor which initializes the data members to 1 after displaying a message that it was called. We will now be able to see which constructor was called when. The constructors now have quite distinct parameter lists, so there's no possibility of the compiler confusing them. The program produces this:

We can see that the default constructor was called five times, once for each element of the array Boxes. The other constructor was called to create the object Cigar. It's clear from the output that the default constructor initialization is working satisfactorily, as the volume of the forth array element is 1.


© 1998 Wrox Press