Modifying Stack to use access control
As a second example, here’s the
Stack turned into a class. Now the nested data structure is
private, which is nice because it ensures that the client programmer will
neither have to look at it nor be able to depend on the internal representation
of the Stack:
//: C05:Stack2.h
// Nested structs via linked list
#ifndef STACK2_H
#define STACK2_H
class Stack {
struct Link {
void* data;
Link* next;
void initialize(void* dat, Link* nxt);
}* head;
public:
void initialize();
void push(void* dat);
void* peek();
void* pop();
void cleanup();
};
#endif // STACK2_H ///:~
As before, the implementation
doesn’t change and so it is not repeated here. The test, too, is
identical. The only thing that’s been changed is the robustness of the
class interface. The real value of access control is to prevent you from
crossing boundaries during development. In fact, the
compiler is the only thing that knows about the protection level of class
members. There is no access control information mangled into the member name
that carries through to the linker. All the protection checking is done by the
compiler; it has vanished by
runtime.
Notice that the interface presented to
the client programmer is now truly that of a push-down
stack. It happens to be
implemented as a linked list,
but you can change that without affecting what the client programmer interacts
with, or (more importantly) a single line of client
code.