CLASS MEMBERS AS FRIENDS

You saw in Chapter 7 how a function can be declared as a friend of a class. This gives the friend function the privilege of free access to any of the class members. Of course, there is no reason why a friend function cannot be a member of another class.

Suppose you define a CBottle class to represent a bottle:

#pragma once
        
class CBottle
{
  public:
    CBottle(double height, double diameter)
    {
      m_Height = height;
      m_Diameter = diameter;
    }
        
  private:
    double m_Height;                        // Bottle height
    double m_Diameter;                      // Bottle diameter
};

You now need a class to represent the packaging for a dozen bottles that automatically has custom dimensions to accommodate a particular kind of bottle. You could define this as:

#pragma once
class CBottle;                              // Forward declaration
        
class CCarton
{
  public:
    CCarton(const CBottle& aBottle)
    {
      m_Height = aBottle.m_Height;          // Bottle height
      m_Length = 4.0*aBottle.m_Diameter;    // Four rows of ...
      m_Width = 3.0*aBottle.m_Diameter;     // ...three bottles
    }
        
  private:
    double m_Length;                        // Carton length
    double m_Width;                         // Carton width
    double m_Height;                        // Carton height
};

The constructor here sets the height to be the same as that of the bottle it is to accommodate, and the length and width are set based on the diameter of the bottle so that 12 fit in the box. The forward declaration for the CBottle class is necessary because the constructor refers to CBottle. As you know by now, this won’t work. The data members of the CBottle class are private, so the CCarton constructor ...

Get Ivor Horton's Beginning Visual C++ 2012 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.