C++ - Default class accessibility

class members are private by default.

class inheritance is private by default.



  // class members are private by default
  class CImage {
      int _width; // private
      int _height; // private
  public:
      void SetWidth(int value) { _width = value;  }
      void SetHeight(int value) { _height = value; }
  
      CImage()
      {
          _width = 0;
          _height = 0;
      }
  };
  

  // class inheritance is private by default
  class CJpegImage : /*private*/ CImage {
      int _compressionLevel;
  public:
      void SetCompressionLevel(int value) { _compressionLevel = value; }
  
      CJpegImage()
      {
          _width = 0; // member is inaccessible. can't access private member of base. use public or protected inheritance.
          _height = 0; // member is inaccessible. can't access private member of base. use public or protected inheritance.
          _compressionLevel = 0;
      }
  };
  

  int main()
  {
      CImage img;
      img.SetWidth(1204);
      img.SetHeight(728);
  
      CJpegImage jpg;
      jpg.SetWidth(1204);
      jpg.SetHeight(728);
      jpg.SetCompressionLevel(100);
  
      return 0;
  }
  

With private inheritance:

  • public members in the base class, become private in the derived class
  • protected members in the base class, become private in the derived class
  • private members in the base class, are hidden to the derived class

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath