We will use the following class definition of an array throughout this section to illustrate the various facets of the class type:
const int ArraySize = 12; // default size
class IntArray {
public:
// operations performed on arrays
IntArray( int size = ArraySize );
~IntArray();
int getValue( int index );
void setValue( int index, int value );
int getSize();
protected:
void checkBounds( int index );
// internal data representation
int size;
int *data;
};
This array class provides several services that the normal array type
does not provide:
class Stack {
int topStack;
Stack stack; // illegal--class definition not yet complete
};
So is this one:
class Stack {
int topStack;
Dlist data;
}
class Dlist { ... }
The above definition would be legal if the Dlist class was declared
before the Stack class.
class Dlist; //forward declaration
class Stack {
int topStack;
Dlist *data; // legal--a forward class declaration has been seen
};
The following is also legal because a class is considered declared
as soon as its class name is seen:
class tree_node {
tree_node *left_child;
tree_node *right_child;
};
IntArray::IntArray( int sz ) {
// allocate an integer array of 'size' elements.
// new returns a pointer to this array or 0
// 0 indicates the program has exhausted its
// available memory: a generally fatal error
size = sz;
data = new int[size];
for ( int ix=0; ix < sz; ix++ )
data[ix] = 0;
}
void IntArray::checkBounds (int index) {
if (index < 0) {
printf("An array index is out of bounds. Its value is %d\n", index);
exit(1);
}
if (index >= size) {
printf("An array index exceeds the bounds of its array. The size\n");
printf("of the array is %d but the value of the index is %d\n",
size, index);
exit(1);
}
}
int IntArray::getValue (int index) {
checkBounds(index);
return data[index];
}
void IntArray::setValue (int index, int value) {
checkBounds(index);
data[index] = value;
}
int IntArray::getSize() { return size; }
IntArray::~IntArray() { delete [] data; }
class Dlist;
class Dlnode {
friend Dlist;
protected:
...
};
The friend declaration gives Dlist access to all of Dlnode's variables
and methods. You use a friend declaration to selectively give outsiders
access to a class's variables/method. Typically this is done when the
outsider needs to work closely with the class or even "own" the class.
For example, the only place a Dlnode will presumably be used is in
a Dlist so in effect the Dlist class "owns" the Dlnode class.
int getSize() { return size; }
int getSize() { return this->size; }
object_table.add(this);