Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

c++ - friend class with inheritance

If I have two Classes as follows with inheritance:

class A
{
    ...
}

class B : public A
{
    ...
}

And a third class with defined as a friend class A:

class C
{
    friend class A;
}

Will I be able to access from class B (which is also an object of type A) all members of class C as if I had defined class B the friend Class in the first place?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

friendship is neither inherited nor transitive. It is strictly one-one relationship between two classes.

class A {
  friend class B;  
  int Aries;
};

class B {
  friend class C;  
  int Taurus;
};

class C {
  int Leo;
  void Capricorn() {
    A a;
    a.Aries = 0;  // this wont work, C is not a friend of A.
                // friendship is not transitive
  }
};

class D : public C {
  void Gemini() {
    B b;
    b.Taurus = 0;  // this wont work, D is not a friend of B.
                   // friendship is not inherited
  }
};    

class E : public B {
  void Scorpio() {
    C c;
    c.Leo = 0; // this wont work either, friendship is not inherited
  }
};

Reference: "The C++ Programming Language" Bjarne Stroustrup

More explanation (mine): If friendship were not one-one, it would be the end of encapsulation. Note that B class can access private members of A only if the class declaration of A declares B as friend. B cannot enforce friendship on A.

Now, if friendship could be inherited, then someone just needs to inherit B to access private members of A, without A having any say in preventing it. Also, allowing friendship to be transitive would lead to other problems, since now B could have a friend C, who in turn could have a friend D, all the way to Z. All of B, C, D, ..., Z can now access A's private members, which would be a disaster.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...