Search code examples
c++friend

Why is a "friend class" not verified for existence?


I used to name my test class as a friend in the class to be tested, in order to enable testing private fields. I noticed that the name of the class is not verified for existence. Is it by intention?


Solution

  • A friend class declaration that uses an elaborated type specifier with non-qualified name of the class is actually a declaration of that class. It introduces the class as a member of the enclosing namespace. It does not require it to be pre-declared

    class C
    {
      friend class X; // OK, introduces '::X'
    };
    

    But if you use a qualified name in a friend class declaration, it will be subjected to a regular qualified name lookup. And it must refer to a previously declared name

    class X {};
    
    class C
    {
      friend ::X; // OK, refers to '::X'
      friend ::Y; // Error, no '::Y' in sight
    };
    

    So, if you want your class name to be "verified for existence", use qualified names in friend declarations.