fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct A
  5. {
  6. int member = 5;
  7.  
  8. void f() const
  9. {
  10. member++; // Won't work (modifiying this->member)
  11. g(); // Won't work (g() is not const)
  12. }
  13.  
  14. void g()
  15. {
  16. // Both works, of course
  17. const_g();
  18. nonconst_g();
  19. }
  20.  
  21. void const_g() const { }
  22. void nonconst_g() { }
  23. };
  24.  
  25. int main() {
  26. A a;
  27. a.f();
  28. a.g();
  29.  
  30. const A b;
  31. b.f(); // Works : f() won't modify b;
  32. b.g(); // Won't work : g() isn't const and might modify b;
  33. return 0;
  34. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In member function 'void A::f() const':
prog.cpp:10:9: error: increment of member 'A::member' in read-only object
   member++; // Won't work (modifiying this->member)
         ^
prog.cpp:11:5: error: passing 'const A' as 'this' argument discards qualifiers [-fpermissive]
   g(); // Won't work (g() is not const)
     ^
prog.cpp:14:7: note:   in call to 'void A::g()'
  void g() 
       ^
prog.cpp: In function 'int main()':
prog.cpp:32:6: error: passing 'const A' as 'this' argument discards qualifiers [-fpermissive]
  b.g(); // Won't work : g() isn't const and might modify b;
      ^
prog.cpp:14:7: note:   in call to 'void A::g()'
  void g() 
       ^
stdout
Standard output is empty