-1

The following code:

#include <iostream>
#include <string>
#include <array>
#include <iterator>

using namespace std;

class obj {
    public:
        obj() = default;
        obj(int i) : i_{i} {}
        void    show()      {cout << "addr = " << this << ", i_ = " << i_ << endl;}
    
    private:
        int i_{0};
};

int main () {

    std::array<obj, 4> o_l {131,223,333,344};

    for (auto const & idx   : o_l) {idx.show();}

    return 0;
}

ends up throwing the following error:

source>: In function 'int main()':
<source>:22:45: error: passing 'const obj' as 'this' argument discards qualifiers [-fpermissive]
   22 |     for (auto const & idx   : o_l) {idx.show();}
      |                                     ~~~~~~~~^~
<source>:12:17: note:   in call to 'void obj::show()'
   12 |         void    show()      {cout << "addr = " << this << ", i_ = " << i_ << endl;}
      |     

My question is - obj::show() is not modifying any class member, so why does the compiler think otherwise?

Ahmed R
  • 13
  • 3

1 Answers1

1

You should make it a const member function explicitly:

    void show() const { cout << "addr = " << this << ", i_ = " << i_ << endl; }
lorro
  • 10,687
  • 23
  • 36