Archived

This topic is now archived and is closed to further replies.

meZmo

C++ Friend classes

Recommended Posts

This is what I''m trying to do:
  
class Q
{
friend class A;

private:
int i;
};

class A
{
virtual void Func() = 0;
};

class B : public A
{
void Func(){ Q myQ; cout << myQ.i; }
};

class C : public A
{
void Func(){ Q myQ; cout << myQ.i; }
};
  
Is there a way to get access to the private variable i in Q, from classes B/C, without explicitly specifying them as friends in Q? -meZ

Share this post


Link to post
Share on other sites
Well, that would work.

But with several variables in Q, this way is more work than just explicitly specifying friend class B and friend class C in Q;

Are there any more "direct" ways to do it?

Share this post


Link to post
Share on other sites
A private variable can only be accessed by the class and its friends.
A protected variable can be accessed by the class, classes that inherit it and its friends.

This is the Law, your compiler will enforce it.

Share this post


Link to post
Share on other sites