0

"this discards qualifiers", what does it mean?

#include <iostream>
using namespace std;
 #include <iostream>
using namespace std;
class b
{
    public:
    
    void show( b &ob)
    {
        //this =ob;
        cout<<"show";
    }
    
};
int main() 
{
 
  b const ob;
  b ob1;
  ob.show(ob1);
    // your code goes here 
    return 0;
}
   
prog.cpp: In function ‘int main()’:
prog.cpp:23:14: error: passing ‘const b’ as ‘this’ argument discards qualifiers [-fpermissive]
   ob.show(ob1);
              ^
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

5

Here you've declared ob to be a const object:

b const ob;

But here you are calling a member function (show) that is not marked as const:

ob.show(ob1);

Mark member functions that does not alter the object (*this) as const:

void show( b &ob) const // <- like this
    {
        //this =ob;
        cout<<"show";
    }

In this particular case, I also recommend that you change show so it does not take any arguments and only show the contents of *this:

#include <iostream>

class b
{
private:
    int example_of_a_member_variable;

public:
    // example of a converting constructor
    explicit b(int value) : example_of_a_member_variable(value) {}
   
    void show() const
    {
        std::cout << example_of_a_member_variable << '\n';
    }
};

int main() {
    b const ob(1234);
    ob.show();           // prints 1234
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 1
    Hmm, I was going to dupe close this, but it's a nicer answer than any of the targets I could find :) – cigien Nov 04 '20 at 11:57
  • @cigien Thanks! Perhaps I should have done the work to find the dupe and answered there instead ... I'm bad at looking for dupes and often just start typing :-) – Ted Lyngmo Nov 04 '20 at 11:59
  • 1
    I understand that, it is often faster to just write the answer. Honestly, the incentive to improve old dupes is not great either :( But if you do want to add an answer to [this](https://stackoverflow.com/questions/8373010/), or [this](https://stackoverflow.com/questions/21189997), that would be great. None of the answers on either question are too exciting :p – cigien Nov 04 '20 at 12:02