fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3. class foo {
  4. public:
  5. int A() const { // const function
  6. return m_var;
  7. }
  8. int const B() { // non const function, but const return type
  9. return m_var;
  10. }
  11. int const& C() const { // non const function, but const reference return type
  12. return m_var;
  13. }
  14. private:
  15. int m_var;
  16. };
  17.  
  18. int main() {
  19. const foo x{};
  20. x.A(); // ok
  21. //x.B(); // not ok -> function B() doesn't guarantee to leave x unchanged.
  22. x.C(); // ok
  23. const int& y = x.C(); // ok (y will not alter m_var.
  24. int& z = x.C(); // not ok since z is not const
  25. return 0;
  26. }
Compilation error #stdin compilation error #stdout 0s 15232KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:24:17: error: binding ‘const int’ to reference of type ‘int&’ discards qualifiers
     int& z = x.C();       // not ok since z is not const
              ~~~^~
stdout
Standard output is empty