fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class my_vector {
  5. public:
  6. double data[6] = {1,2,3,4,5,6};
  7. double & operator()(size_t i) {
  8. std::cout<<"Calling non-const ()"<<std::endl;
  9. return data[i];
  10. }
  11. double operator()(size_t i) const {
  12. std::cout<<"Calling const ()"<<std::endl;
  13. return data[i];
  14. }
  15. };
  16.  
  17. void withConst(const my_vector &v) {
  18. double vv = v(0);
  19. std::cout<<"v(0) = "<<vv<<std::endl;
  20. // v(0) = 4.0; // Does not compile
  21. }
  22.  
  23. void withNonConst(my_vector &v) {
  24. v(0) = 4.0;
  25. double vv = v(0);
  26. std::cout<<"v(0) = "<<vv<<std::endl;
  27. }
  28.  
  29. int main() {
  30. my_vector vec;
  31. withConst(vec);
  32. withNonConst(vec);
  33. return 0;
  34. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Calling const ()
v(0) = 1
Calling non-const ()
Calling non-const ()
v(0) = 4