O'Reilly logo

Practical C++ Programming, 2nd Edition by Steve Oualline

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 solution ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required