Question

I am a bit confused about how to accomplish the following using friend functions.

Say I have a class A whose member function 'f' is to be declared friend to class B.

The normal solution would be this, as I understand:

Define class A with 'f' only being declared not defined

Define class B including friend declaration of 'f'

Define 'f'

Now, what if class A were to have data members which are of class type B or a container of B type elements, like vector < B >.

Forward declaring class B seems to work (i.e. no compiler warnings/errors) but i am not sure if it is legal as per C++11 standard. Also, such a solution won't allow me to use a constructor of class B to provide in-class initializer for class B type members of A. What would be the best possible way to accomplish all of this in conformance to C++11?

I tried finding a solution from the standard itself but couldn't find mention of such a scenario. I'd be happy if someone could point me to it.

PS I am really a beginner, so please don't assume otherwise in your answers. I wouldn't mind detailed answers though:)

Was it helpful?

Solution

You should read the MSDN article about this issue: Class Member Functions and Classes as Friends

Basically what you need to do is have a class type A with a function f() , and then you declare in class type B that there exists a function A::f() which will be your friend.

The MSDN example shows this well:

class A {
public:
   int Func1( B& b );

private:
   int Func2( B& b );
};

class B {
private:
   int _b;

   // A::Func1 is a friend function to class B
   // so A::Func1 has access to all members of B
   friend int A::Func1( B& );
};

int A::Func1( B& b ) { return b._b; }   // OK
int A::Func2( B& b ) { return b._b; }   // C2248
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top