Chapter 15

1: What's wrong with the following attempts at establishing friends?
  1. class snap {
        friend clasp;
         ...
    } ;
    class clasp {  ... } ;
    
  2. class cuff {
    public:
          void snip(muff &) {  ... }
          ...
    } ;
    class muff {
         friend void cuff::snip(muff &);
         ...
    } ;
    
  3. class muff {
          friend void cuff::snip(muff &);
         ...
    } ;
    class cuff {
    public:
          void snip(muff &) {  ... }
          ...
    } ;
    
A1:
  1. The friend declaration should be as follows:

    friend class clasp;
    
  2. This needs a forward declaration so that the compiler can interpret void snip(muff &):

    class muff;    // forward declaration
    class cuff {
    public:
        void snip(muff &) { ... }
        ...
    };
    class muff {
        friend void cuff::snip(muff &);
        ...
    };
    
  3. First, the cuff class declaration should precede the muff class so that the compiler can understand ...

Get C++ Primer Plus, Fourth 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.