C++: friend classes without breaking encapsulation?

rflcptr

Supreme [H]ardness
Joined
Mar 27, 2008
Messages
6,928
I've created a friend to the Tv class that gives Remote objects private access. Without success, though, I'm trying to create some friends to Remote so that objects of the Tv class, exclusively, can modify Remote private data without my having to resort to giving both classes (declaring all functions of both classes as friends) unnecessary access to each other's private data. In short, just some limited mutual classes.

Is it possible to extend Remote's declaration below Tv's, so that the compiler can find the Tv declaration? Or does constructing limited friend classes only work in one direction?
Code:
class Tv;

class Remote
{
private:
        ...
public:
        ...
	[COLOR="Yellow"]friend void Tv::buzz(Remote & r);
	friend void Tv::toggle(Remote & r); // compiler C2027 errors: use of undefined type 'Tv'[/COLOR]
};
class Tv
{
private:
        ...
public:
        ...
	friend void Remote::set_chan(Tv & t, int c);     // works
};

// Remote, Tv, and friend definitions
...

Thanks a bunch!
 
Last edited:
Figured it out. Because the Tv forward declaration doesn't reveal anything about the class to Remote, Remote is unable to declare a friend as a member of Tv.

Here I come, "friend class Tv;" and "friend class Remote;". :p
 
Your diagnosis is correct, and co-friending these classes will fix the problem. Is that an adequate design for you? Are the relationships between these classes and the classes in the rest of the app affected by this choice?
 
It works, it just "feels" goofy since I can now just directly change Tv data from any Remote function, all without making a single call to a Tv function. And vice-versa.
 
Back
Top