fork download
  1. #include <iostream>
  2.  
  3. using Color = int;
  4. struct Shape
  5. {
  6. double area = 0;
  7. };
  8.  
  9. class Geometry
  10. {
  11. public:
  12. // everybody can alter the color of the geometry, so
  13. // they get a mutable reference
  14. Color& color() { return m_color; };
  15.  
  16. // not everybody can alter the shape of the Geometry, so
  17. // they get a constant reference to the shape.
  18. Shape const& shape() const { return m_shape; };
  19.  
  20. protected:
  21. // derived classes can alter the shape, so they get
  22. // access to the mutable reference to alter the shape.
  23. Shape & shape() { return m_shape; };
  24.  
  25. private:
  26. Shape m_shape;
  27. Color m_color;
  28. };
  29.  
  30.  
  31. void someFunction(Geometry & g)
  32. {
  33. std::cout << g.shape().area << std::endl;
  34. }
  35.  
  36. int main ()
  37. {
  38. Geometry g1;
  39. someFunction(g1);
  40. return 0;
  41. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘void someFunction(Geometry&)’:
prog.cpp:23:11: error: ‘Shape& Geometry::shape()’ is protected
   Shape & shape() { return m_shape; };
           ^
prog.cpp:33:24: error: within this context
   std::cout << g.shape().area << std::endl;
                        ^
stdout
Standard output is empty