C++ - Default struct accessibility

struct members are public by default.

struct inheritance is public by default.



  // struct members are public by default
  struct Image {
      int Width;
      int Height;
  };
  

  // struct inheritance is public by default
  struct JpegImage : /*public*/ Image {
      int CompressionLevel;
  };
  

  int main()
  {
      struct Image img;
      img.Width = 1024;
      img.Height = 768;
  
      struct JpegImage jpg;
      jpg.Width = 1024;
      jpg.Height = 768;
      jpg.CompressionLevel = 1;
  
      return 0;
  }
  

With public inheritance:

  • public members in the base class, stay public in the derived class
  • protected members in the base class, stay protected 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