Compiler error for modifying non-const object
#include "iostream"
#include "vector"
class ABC {
private:
bool m_b;
public:
ABC() : m_b(false) {}
ABC& setBool(bool b) {
m_b = b;
return *this;
}
bool getBool() const {
return m_b;
}
};
void foo(const std::vector<ABC> &vec) {
vec[0].setBool(true);
}
int main(int argc, char*argv[]) {
std::vector<ABC> vecI;
ABC i;
vecI.push_back(i);
foo(vecI);
}
I get this error when compiling: passing const ABC
as an argument this
ABC& ABC::setBool(bool)
discards qualifiers
Any ideas why this would happen as this object is not a constant.
source to share
foo accepts vec by reference-to-const, and you cannot change the constant. So either remove the line that calls setBool, or if you really want to set bool, change the argument type to std :: vector &.
Or to be more strict in implementation ... You see, these two functions exist:
T& vector<T>::operator[](int);
T const& vector<T>::operator[](int) const;
When you call "vec [i]" on a const object, only the second is valid, so it is selected. But this overload obviously returns T const &, and that's what you can't change.
The object is probably a constant. Although the vector contains an ABC and not a const ABC, the vector itself is const, so when you call operator [] on it, the const version of the operator is used. The const version of the [] operator on a vector returns a vector :: const_reference. So from what I can tell you are trying to call a non-const method on const ABC &.
source to share