Need to declare a class ( defined in cpp file ) as friend

Hello,

I have a namespace and class defined inside a cpp file (say x.cpp ). I want to declare this class as 'friend' inside another header (say y.h), but the header won't recognize the namespace.

Now, when I put the namespace in another header (x.h) and include it in y.h, I get a re-definition error ( also in x.cpp ). I can't remove the namespace definition from x.cpp, since it has been put together by a framework for me, and I won't be able to use the framework otherwise.

Does this mean I can't declare this class as friend of any other class ?

Regards,
Raj Abhishek
Last edited on
Make a forward declaration of the class in the correct namespace before the friend declaration.

1
2
3
4
5
6
7
8
9
namespace N
{
	class C;
}

class OtherClass
{
	friend N::C;
};
Thanks a lot Peter .. You made my day !

One more question though. Now I want a function within C as a friend function for OtherClass, without making the whole class C as a friend. Possible through this approach ??

@Tarik thanks for your link. I'll go through it right away !

Regards,
Raj Abhishek
No. The class has to be defined for you to acknowledge the existence of its members.
rajcrec wrote:
Now I want a function within C as a friend function for OtherClass, without making the whole class C as a friend.

For this you need the class definition of C. Normally class definitions are put in header files that you can easily include if you need them. As I understand it you say that the class definition is in x.cpp. If you can't move the class definition into a header I don't know how you should do it.
Topic archived. No new replies allowed.