What's the difference between friendship and inheritance?

前端 未结 4 1113
轻奢々
轻奢々 2021-01-01 06:12

Suppose there are two classes A and B:

class A {};
class B {};

In what aspects differ the two examples below?

Example 1:

         


        
4条回答
  •  太阳男子
    2021-01-01 06:34

    There are several big differences. Inheritance and friendship are very different.

    With friendship, class C is NOT an instance of class A or class B. Therefore, if you have a function like:

    void processMyClass(A* a);
    

    you cannot pass it an instance of C whereas, if C subclasses A (publicly), it IS an instance of A.

    With friendship, class A and B can touch all the private member data and functions of C. With inheritance, class C can touch the public and protected members of A and B.

    Friendship is not inherited. This means, for example:

    class D : public C
    {
    private:
       void foo() {
          // A and B cannot call this function
       }
    }
    

提交回复
热议问题