Create an Array of Objects in C++



This program shows you how to create an array of objects in C++. The class cl has two variables and two functions to retrieve the values of the two variables. It also has a constructor that is used to initialize the two variables in the parameters when the object is created. See code below:


#include <iostream.h>
#include <conio.h>

class test_class
{
      int h;
      int i;
      public:
      test_class(int j, int k)
      {
            h=j;
            i=k;
      } // constructor with 2 parameters
      int get_i() {return i;}
      int get_h() {return h;}
};

int main()
{
      clrscr();
      test_class ob[3] = // initialize 3 objects
      {
      cl(1, 2), // h = 1, i = 2 for first object
      cl(3, 4), // h = 3, i = 4 for second object
      cl(5, 6)  // h = 5, i = 6 for third object
      }

int i;

for(i=0; i<3; i++) // Display all variables in the 3 objects
{
      cout << ob[i].get_h(); // Display h
      cout << ", ";
      cout << ob[i].get_i() << "\n"// Display i
}

getch();
return 0;
}
Custom Search