20-CS-122-001 Computer Science II Spring 2012
Arrays of Objects

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source

#include <stdio.h>
#include <iostream>
using namespace std;

#define HSIZE 5
#define VSIZE 10

// Class of simple object to store - each takes 400 bytes
class Object {
   int array[100];
 public:
   Object () { }
   int valueOf() { return array[0]; }
   void setValue(int n) { array[0] = n; }
};

// Print the array of objects (50 in this case)
void testPrint(Object *u) {
   for (int j=0 ; j < VSIZE ; j++) {
      cout << "\n";      
      for (int k=0 ; k < HSIZE ; k++)
         cout << "\t" << u[j*HSIZE+k].valueOf();
   }
   cout << "\n";
}

// The "new" line creates space for 50 objects (20000 bytes)
// Notice [] dereferences one level so "." is used instead of "->"
int main() {
   int count = 0;
   Object *o = new Object[HSIZE*VSIZE];
   for (int j=0 ; j < VSIZE ; j++)
      for (int k=0 ; k < HSIZE ; k++)
         o[j*HSIZE+k].setValue(count++);
   testPrint(o);
   printf("\nHigh address: %u\nLow address:  %u\n", &o[HSIZE*VSIZE], &o[0]);
}