Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiler "error: passing ‘const something’ as ‘this’ argument discards qualifiers"

Tags:

c++

I am making a custom list using templates in C++ and get some compilation error.
The code is very large in length , so here is a small snippet of the code from where the error is coming. Compilation error is given below. You can compile it your own system to see the same error.

#include <iostream>
using namespace std;

template <class T>
class sortedList
{
    int m_count;
    public:
    sortedList(){m_count = 0;}
    int length(){ return m_count; }

};


    void output(const sortedList<int>& list)
    {
        cout << "length" << list.length() << endl;
        return;
    }

int main() {
    // your code goes here

    sortedList <int> list1;
    output(list1);

    return 0;
}

I am getting compilation error :

prog.cpp: In function ‘void output(const sortedList<int>&)’:
prog.cpp:17:35: error: passing ‘const sortedList<int>’ as ‘this’ argument discards qualifiers [-fpermissive]
   cout << "length" << list.length() << endl;
                                   ^
prog.cpp:10:6: note:   in call to ‘int sortedList<T>::length() [with T = int]’
  int length(){ return m_count; }
like image 862
Bhawan Avatar asked Oct 11 '17 05:10

Bhawan


2 Answers

You have to make length to be const-qualified:

int length(){ return m_count; }

int length() const { return m_count; }
like image 189
Yunnosch Avatar answered Dec 08 '22 00:12

Yunnosch


  1. As already mentioned, one option is to make length const-qualified.
  2. Another option is to use const_cast within the output function.
sortedList<int>& ref = const_cast <sortedList<int>&>(list);
cout << "length" << ref.length() << endl;

(2) is especially useful when we don't have the luxury to update the class method mentioned in (1).

like image 36
monk Avatar answered Dec 08 '22 00:12

monk