Default inheritance access specifier

前端 未结 9 1718
北海茫月
北海茫月 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 
    
    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;
    }
    

提交回复
热议问题