C++ Linked Lists   «Prev  Next»
Lesson 3A safe array
ObjectiveGrouping arrays in a class

Grouping C++ Class Arrays

Examine creating "has-a" relationship by making the safe array class a member of another class. Now that we have created a safe array, let's use our class vect as a member of the class pair_vect. Using a class as a member of another class is known as the hasa relationship. Complicated objects can be designed from simpler ones by incorporating them with the hasa relationship.
#include "vect.h" //the safe array class
//from the previous lesson

class pair_vect {
 public:
  pair_vect(int i) : a(i), b(i), size(i){ }
  int& first_element(int i);
  int& second_element(int i);
  int ub()const {return size -1;}
  private:
  vect a, b;
  int size;
};

int& pair_vect::first_element(int i){ 
return a.element(i); 
}

int& pair_vect::second_element(int i)
{ return b.element(i);}

Notice how the pair_vect constructor is a series of initializers. The initializers of the vect members a and b invoke vect::vect(int). Let's use the pair_vect class to build a table of age and weight relationships.
int main()
{
int     i;
pair_vect age_weight(5);  //age and weight

cout << "table of age, weight\n";
for (i = 0; i <= age_weight.ub(); ++i) {
age_weight.first_element(i) = 21 + i;
age_weight.second_element(i) = 135 + i;
cout << age_weight.first_element(i) << ","
<< age_weight.second_element(i)<< endl;
}
}

SEMrush Software