Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

error: passing 'const obj' as 'this' argument discards qualifiers

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should make it a const member function explicitly:

    void show() const { cout << "addr = " << this << ", i_ = " << i_ << endl; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading