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; }
You have to make length
to be const-qualified:
int length(){ return m_count; }
→
int length() const { return m_count; }
length
const-qualified.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With