How come forward declaration is not needed for friend class concept?

本秂侑毒 提交于 2019-11-28 11:05:38
Luchian Grigore

You're right, the friend declaration is kind of like a forward declaration.

The following compiles:

class A;
class B
{
   friend A;
};

or

class B
{
   friend class A;
};

this does not:

class B
{
   friend A;
};

It's not actually the friend declaration that forward-declares class A, but the class keyword. That's why the second example doesn't work, because it doesn't know what A is. If you declare A beforehand, like in the first snippet, it can resolve A to a class declaration.

I stand corrected.

friend class TLS;

This syntax is a declaration in itself, that is why you don't need an extra previous declaration of the type. Note that the friend declaration is slightly different (specially for functions) than a declaration in the enclosing namespace.

In particular, unless there is also a declaration in the enclosing namespace, a function declared in a friend declaration can only be found by argument dependent lookup (and cannot be defined outside of the class). The same goes for classes, unless there is also a declaration at namespace level, the type so declared will not be available outside of the class declaring it as a friend.

class B {
   friend class A;
};
//A foo();    // Error: A is not declared here!
class A;
A foo();      // Fine

forward declaration does not need to be at the top of the file as follows

class A;
class C;
class D;
class B
{
   A* a;
   C* c;
   D* d;
};

is the same as

class B
{
   class A* a;
   class C* c;
   class D* d;
};

the recommended friend syntax just uses the later

Does that mean that a friend class declaration is a forward declaration all in it self?

Yes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!