System.Object being the base class

后端 未结 8 1001
北荒
北荒 2020-12-03 15:47

This question may be usual for many, i tried for an hour to understand the things but getting no proper explanation.

MSDN says, System.Object is the ultimate

8条回答
  •  时光取名叫无心
    2020-12-03 16:20

    Seems like you have a slight confusion with the meaning of 'multiple inheritance'?

    Multiple inheritance is not when 'B inherits from A, and A inherits from O'. That's just a simple inheritance hierarchy -- which is a feature of C++, Java and C#.

    In the above case, we'd say that B inherits directly from A, and inherits indirectly from O. B inherits the (non-private) members from A, and, indirectly, the (non-private) members of O.

    C++ in addition supports true multiple inheritance, which can sometimes be called 'mix-in inheritance': An example of multiple inheritance would be

     class A : public O {};
     class B : A, O {};
    

    Here B inherits directly from O, and also inherits directly from A -- In this case two copies of O's members exist in B, and to access the members of B that come from O, you need to specify which of those copies you want:

    e.g. b.O::omember; or b.A::omember;

    With large C++ class frameworks, you can often get undesired copies of base classes in your derived classes when you use multiple inheritance. To get round this, C++ provides virtual inheritance, which forces only one copy of the virtual base class to be inherited: The following example should make this clear (or make it even more confusing!)

    // Note, a struct in C++ is simply a class with everything public
    struct O { int omember; };
    struct A1 :  O {};
    struct B1 :  O, A1 {};
    
    struct A2 :  virtual O {};
    struct B2 :  virtual O, A2 {};
    
    B1 b1;
    B2 b2;
    
    // There are two 'omember's in b1
    b1.omember; // Compiler error - ambiguous
    b1.A1::omember = 1;
    b1.O::omember = 2;
    
    // There's only one 'omember' in b2, so all the following three lines
    // all set the same member
    b2.A2::omember = 1;
    b2.O::omember = 2;
    b2.omember = 3;
    

提交回复
热议问题