fork download
  1. #include <iostream>
  2. using namespace std;
  3. class bar {
  4. public:
  5. void change_it() {}
  6. void read_it() const {}
  7. };
  8. class foo {
  9. public:
  10. bar A() const { // const function
  11. return m_var;
  12. }
  13. bar const B() { // non const function, but const return type
  14. return m_var;
  15. }
  16. bar const& C() const { // non const function, but const reference return type
  17. return m_var;
  18. }
  19. //private:
  20. bar m_var;
  21. };
  22.  
  23. int main() {
  24. const foo x{};
  25. x.A(); // ok
  26. //x.B(); // not ok -> function B() doesn't guarantee to leave x unchanged.
  27. x.C(); // ok
  28. const bar& y = x.C(); // ok (y will not alter m_var).
  29. //int& z = x.C(); // not ok since z is not const
  30.  
  31. foo u{};
  32. u.B(); // ok
  33. u.B().read_it(); // ok
  34. //u.B().change_it(); // not ok because of const return value.
  35.  
  36. return 0;
  37. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
Standard output is empty