vector of friend class objects

It dawned on me today that since learning how to use friend classes I've never had a need for them, now however, I do.

I'd like to store a vector of friend class objects, the syntax looks right to me but the compiler still throws up an error, what am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class A{
public:
    A(int val) : m_val(val) {}
private:
    int m_val;    
};

class B{
public:
    void AddValue(int val)
    { 
        m_vec.push_back(A(val)); 
    }

    void PrintVec()
    {
        for (int i=0; i<m_vec.size(); i++)
        {
	    std::cout << m_vec.at(i).m_val << "\n"; // error C2248: 'A::m_val' : cannot access private member declared in class 'A'
        }
    }

private:
    std::vector<friend class A> m_vec;
};


I could of course just make a load of getter functions in my equivalent of the 'A' class, but only one class needs access to A's private members and several other classes need access to its public functions. If what I'm trying to do really isn't possible then this might turn out to be a design question.
You're doing it backwards.

If B is accessing A, then A needs to declare B as it's friend... not the other way around.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A{
public:
    A(int val) : m_val(val) {}
private:
    int m_val;    
    friend class B;  // <- B is the friend, not A
};


class B
{
//...
  std::cout << m_vec.at(i).m_val << "\n";   // now this will work, because B is a friend

//...

std::vector<class A> m_vec;  // <- get rid of the friend keyword here
};
D'oh! Thanks Disch, shows how little I actually remember about friend classes.
Topic archived. No new replies allowed.