friendship and inheritance problem

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class MainClass
{
friend class Base;
protected:
    int x;
public:
    MainClass(int x)
      {
        this->x=x;
      }
// ...

};


class Base
{
public:
    MainClass *mc;
// ...
};


class Other:public Base
{
public:
    Other(MainClass *mainclass) {mc=mainclass;}
    int get_x()
      {
         return mc->x;
      }

};





int main()
{

MainClass mc(112);
Other ot(&mc);

std::cout<<ot.get_x();


}

What I get is
error: 'int MainClass::x' is protected within this context: [...]


I want to make that Other could access MainClass::x. I know that I could simply add friend class Other; to Mainclass but maybe it's possible to avoid this?

Thanks for help.
As you've discovered, friendship is not inherited. Just because Base is a friend of MainClass doesn't mean children of Base are.

If you find yourself wanting to do this, it might be a design flaw. Perhaps you need to reconsider your use of friendship here?

One way around it is kind of ugly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Base
{
protected:
  int getmcx()
  {
    return mc->x;
  }
};

//...

class Other : public Base
{
  int get_x()
  {
    return getmcx();
  }
};


I don't recommend this approach because it's a little absurd, but it makes sense in some practical situations.
OK, thanks.
Topic archived. No new replies allowed.