20-CS-122-001 Computer Science II Spring 2012
What's Up With **?

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

Prev      Next      Lectures      Source

#include <iostream>
using namespace std;

// What is "**"?  By comparison to the equivalent Java code on the next slide
// we see that "**" is not so mysterious after all!  The problem really is
// that C++ allows three ways to build an array of objects whereas Java
// allows only one!!  Below we show the three ways of building object arrays
// in C++.  The following class "A" will bear the brunt.
class A {
public:
   int number;
   A () { number = 134; }
   A (int number) { this->number = number; }
};

int main () {
                /***1. Array of pointers to objects***/
   A **a;
   a = new A*[10];                           // ask for an array of pointers
   for (int i=0 ; i < 10 ; i++) a[i] = new A(i);  // fill the array elems
   
   for (int i=0 ; i < 10 ; i++) cout << a[i]->number << " ";
   cout << "\n";

      /***2. Array of objects, pointer variable as reference***/

   A *b;
   b = new A[10];  // ask for an array of objects, use the default constructor
   for (int i=0 ; i < 10 ; i++) cout << b[i].number << " "; 
   cout << "\n";

   for (int i=0 ; i < 10 ; i++) b[i].number = i;  // set "number" manually

   for (int i=0 ; i < 10 ; i++) cout << b[i].number << " ";
   cout << "\n";

            /***3. Array of objects, constant reference***/

   A c[10]; // ask for an array of objects, use the default constructor
   for (int i=0 ; i < 10 ; i++) cout << c[i].number << " ";
   cout << "\n";

   for (int i=0 ; i < 10 ; i++) c[i].number = i;  // set "number" manually

   for (int i=0 ; i < 10 ; i++) cout << c[i].number << " ";
   cout << "\n";
}
// Output:
//    10 11 12 13 14 15 16 17 18 19
//    134 134 134 134 134 134 134 134 134 134 
//    10 11 12 13 14 15 16 17 18 19
//    134 134 134 134 134 134 134 134 134 134 
//    10 11 12 13 14 15 16 17 18 19