Difference between private, public, and protected inheritance

后端 未结 16 2157
灰色年华
灰色年华 2020-11-21 06:15

What is the difference between public, private, and protected inheritance in C++?

16条回答
  •  半阙折子戏
    2020-11-21 06:37

    Limiting the visibility of inheritance will make code not able to see that some class inherits another class: Implicit conversions from the derived to the base won't work, and static_cast from the base to the derived won't work either.

    Only members/friends of a class can see private inheritance, and only members/friends and derived classes can see protected inheritance.

    public inheritance

    1. IS-A inheritance. A button is-a window, and anywhere where a window is needed, a button can be passed too.

      class button : public window { };
      

    protected inheritance

    1. Protected implemented-in-terms-of. Rarely useful. Used in boost::compressed_pair to derive from empty classes and save memory using empty base class optimization (example below doesn't use template to keep being at the point):

      struct empty_pair_impl : protected empty_class_1 
      { non_empty_class_2 second; };
      
      struct pair : private empty_pair_impl {
        non_empty_class_2 &second() {
          return this->second;
        }
      
        empty_class_1 &first() {
          return *this; // notice we return *this!
        }
      };
      

    private inheritance

    1. Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here

      template
      struct string : private StorageModel {
      public:
        void realloc() {
          // uses inherited function
          StorageModel::realloc();
        }
      };
      

    public member

    1. Aggregate

      class pair {
      public:
        First first;
        Second second;
      };
      
    2. Accessors

      class window {
      public:
          int getWidth() const;
      };
      

    protected member

    1. Providing enhanced access for derived classes

      class stack {
      protected:
        vector c;
      };
      
      class window {
      protected:
        void registerClass(window_descriptor w);
      };
      

    private member

    1. Keep implementation details

      class window {
      private:
        int width;
      };
      

    Note that C-style casts purposely allows casting a derived class to a protected or private base class in a defined and safe manner and to cast into the other direction too. This should be avoided at all costs, because it can make code dependent on implementation details - but if necessary, you can make use of this technique.

提交回复
热议问题