Thread: Finding friends

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jun 2008
    Location
    Somewhere in Europe
    Posts
    99

    Finding friends

    I am trying to decipher the following paragraph from chapter 11.5.1 of Bjarne Stroustrup's The C++ Programming Language:

    "A friend class must be previously declared in an enclosing scope or defined in the non-class scope immediately enclosing the class that is declaring it a friend. Scopes outside the innermost enclosing namespace scope are not considered."

    The following compliles and runs fine with Code::Blocks GCC, so I presume that the word "previously" relates only to "declared" and not to "defined", since the definition of class Y comes after that of class X:

    Code:
    #include <iostream>
    
    using namespace std;
    
    namespace out
    {
    class X
    {
        int i;
        public:
        X(int j = 0):i(j){}
        friend class Y;
    };
    
     class Y
    {
        public:
        void f(X x){cout << x.i;}
    };
    
    }
    
    int main()
    {
        out::X x(101);
        out::Y y;
        y.f(x);
    }
    Likewise, the following compliles and runs fine with the same compiler, so I presume the second sentence relates only to definition and not to declaration, since the declaration of class Y is outside the innermost enclosing namespace and yet it is evidently being considered:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class Y;
    
    namespace out
    {
    class X
    {
        int i;
        public:
        X(int j = 0):i(j){}
        friend class Y;
    };
    }
    
     class Y
    {
        public:
        void f(out::X x){cout << x.i;}
    };
    
    int main()
    {
        out::X x(101);
        Y y;
        y.f(x);
    }
    To sum up, I would interpret the text to mean the following:

    A friend class must be declared previously in an enclosing scope or defined somewhere in the non-class scope immediately enclosing the class that is declaring it a friend. In the latter case, scopes outside the innermost namespace scope or not considered.

    Is that right?
    Last edited by DL1; 07-28-2009 at 08:50 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. tools for finding memory leaks
    By stanlvw in forum C++ Programming
    Replies: 4
    Last Post: 04-03-2009, 11:41 AM
  2. Finding primes
    By starripper in forum C++ Programming
    Replies: 19
    Last Post: 01-14-2006, 04:17 PM
  3. Finding parents in a general tree
    By neandrake in forum C++ Programming
    Replies: 4
    Last Post: 03-22-2005, 08:19 PM
  4. finding an element in a linked list from the end.
    By anoopks in forum C Programming
    Replies: 9
    Last Post: 04-08-2004, 09:00 AM
  5. MFC :: Finding Child Window of a CWnd* Object?
    By SyntaxBubble in forum Windows Programming
    Replies: 2
    Last Post: 09-06-2003, 09:06 AM