Default inheritance access specifier

前端 未结 9 1677
北海茫月
北海茫月 2020-12-04 19:12

If I have for example two classes A and B, such that class B inherits A as follows:

class B: public A

相关标签:
9条回答
  • 2020-12-04 19:39

    When you inherit a class from another class, then default access specifier is private.

    #include <stdio.h>
    
    class Base {
    public:
    int x;
    };
    
    class Derived : Base { }; // is equilalent to class Derived : private Base       {}
    
    int main()
    {
     Derived d;
     d.x = 20; // compiler error becuase inheritance is private
     getchar();
     return 0;
    }
    

    When you inherit a structure from another class, then default access specifier is public.

    #include < stdio.h >
      class Base {
        public:
          int x;
      };
    
    struct Derived: Base {}; // is equilalent to struct Derived : public Base {}
    
    int main() {
      Derived d;
      d.x = 20; // works fine becuase inheritance is public
      getchar();
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-04 19:39

    The default type of the inheritance is private in C++.

    class B:A
    {};
    

    is equivalent to

    class B: private A
    {};
    
    0 讨论(0)
  • 2020-12-04 19:40

    Just a small addition to all the existing answers: the default type of the inheritance depends on the inheriting (derived) type (B in the example), not on the one that is being inherited (base) (A in the example).

    For example:

    class A {};
    struct B: /* public */ A {};
    
    struct A {};
    class B: /* private */ A {};
    
    0 讨论(0)
提交回复
热议问题