Chapter 14. More on Classes

This method is, to define as the number of a class the class of all classes similar to the given class.

—Bertrand Russell, Principles of Mathematics, Part II, Chapter 11, Section iii, 1903

C++ has many bells and whistles that give you a lot of flexibility in designing your classes. For example, the friend keyword lets a class specify ordinary functions that are allowed to access its private data. This section also covers constant members as well as how to constrain specific data using the keyword static.

Friends

In Chapter 13, you defined a basic stack class. Suppose you want to write a function to see whether two stacks are equal. At first glance this is simple. The function looks like Example 14-1.

Example 14-1. stack_c/s_equal.cpp

/********************************************************
 * stack_equal -- Test to see if two stacks are equal   *
 *                                                      *
 * Parameters                                           *
 *      s1, s2 -- the two stacks                        *
 *                                                      *
 * Returns                                              *
 *      0 -- stacks are not equal                       *
 *      1 -- stacks are equal                           *
 ********************************************************/
int stack_equal(const stack& s1, const stack& s2)
{
    int index;  // Index into the items in the array

    // Check number of items first
    if (s1.count != s2.count)
        return (0);

    for (index = 0; index < s1.count; ++index) {

        assert((index >= 0) && 
               (index < sizeof(s1.data)/sizeof(s1.data[0])));

        assert((index >= 0) && 
               (index < sizeof(s2.data)/sizeof(s2.data[0])));

        if (s1.data[index] != s2.data[index])
            return (0);
    }
    return (1);
}

Like many programs, this ...

Get Practical C++ Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.