Friendship and inheritance

Hi!

I could use some help with inheritance and friendship. I have the following classes:

1
2
3
4
5
6
7
class B
{
private:
    //... A bunch of functions here
    int PrivateInteger;
    friend int A::f(B*);
}


1
2
3
4
5
6
7
8
9
10
11
12
class A
{
public:
    virtual int f(B*);
}

int A::f(B* b)
{
    //...
    b->PrivateInteger; //Allowed
}


1
2
3
4
5
6
7
8
9
10
11
class ChildOfA: public A
{
public:
    //... A bunch of functions here
}

int ChildOfA::f(B* b)
{
    //...
    b->PrivateInteger; //Not allowed
}


I would like all of A's children to have access to B in their overloaded f(B*)-function. Right now, A is allowed, and ChildOfA is not, to access the privates of B. Friendship is not inherited, so much I've read. Is there any way to work around this? I don't want to add a massive list of friends in class B.

Cheers!

Bobruisk
Last edited on
In my experience, if you find yourself using friends, your probably doing the wrong thing.

If you had to draw a class diagram, what would be the relationship between the parties?
B is a kind of state class; it stores info about a certain player (location, speed, hit points if you like etc etc).

A, or rather each child of A is a kind of Statement class, it acts upon a state class (B) and returns either true or false. For example, "Speed > 20". A and offspring requires full access to B's internal variables in order to evaluate an arbitrary statement.

I need these statements to be their own objects so that I can build arbitrary combinations of them, and i need them to conform to the same interface (Hence the inheritance of A and the virtual function int f(B*))

Bobruisk
Wait... what's the problem?

1
2
3
4
5
int ChildOfA::f(B* b)
{
    //...
    b->PrivateInteger; //Not allowed
}


If 'b' is passed as a paramter, this certainly is allowed.

If it's a member of A and you're not passing it as a parameter, but you want child classes to have access, make it protected instead of private.
Last edited on
Hmm, not working for me. Only A is allowed to acces the privates of B, ChildOfA is not. Are you saying, if i change B to:

1
2
3
4
5
6
7
class B
{
protected:
    //... A bunch of functions here
    int PrivateInteger;
    friend int A::f(B*);
}


, it should work? Doesn't seem to be working for me!
Can't you provide that information thru public methods in B?
Oh whoops, I totally misunderstood the question. I'm sorry, you're right, that's not allowed.

+1 to kbw. Why can't you make a public interface for B?
I took the public methods route you suggested, thank you!
Topic archived. No new replies allowed.