Question

I'm currently reading C++ Primer and am at the point of class friends and member function friends and I'm having trouble figuring out how to get the code that has the following pseudoform to work:

class B;

class A {
public:
    A(int i): someNum(i) { }
private:
    int someNum;
    friend void B::someMemberFunction(Args); // Compile error: Incomplete Type
};

class B {
public:
    void someMemberFunction(Args) { /* doStuff */ }
private:
    vector<A> someVector { A(5) };
};

If you try to compile in this form it gives the incomplete type error on the friend line. So the solution is to move the class B definition above class A:

class A;

class B {
public:
    void someMemberFunction(Args) { /* doStuff */ }
private:
    vector<A> someVector { A(5) }; // Compile error: Incomplete Type
};

class A {
public:
    A(int i): someNum(i) { }
private:
    int someNum;
    friend void B::someMemberFunction(Args);
};

However now on the vector line, it doesn't know how to create an object of type A, since A has yet to be defined. So then A needs to be defined before B. But now we've arrived back at the original problem. I think this is called circular dependency? I don't know how to fix this with forward declarations.

Any help would be appreciated. Thanks.

Was it helpful?

Solution

I think you will either have to make the whole of class B a friend (which removes a dependency in A anyway so it's probably a good thing), or use a constructor instead of the in-class initializer.

class B;

class A {
public:
    A(int i): someNum(i) { }
private:
    int someNum;
    friend class B;
};

class B {
public:
    void someMemberFunction() { /* doStuff */ }
private:
    vector<A> someVector { A(5) };
};

Or this

class A;

class B {
public:
    B();
    void someMemberFunction() { /* doStuff */ }
private:
    vector<A> someVector;
};

class A {
public:
    A(int i): someNum(i) { }
private:
    int someNum;
    friend void B::someMemberFunction();
};

B::B(): someVector{A(5)} { }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top