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.

-1


source to share


4 answers


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.

+6


source


foo

takes on a value const vector &

, which means that the contents of the vector cannot be changed. This, in turn, means that you are not allowed to call a non-const member function on any of the vec

and elements setBoo

.



0


source


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 &.

0


source


As another workaround, you can store pointers to ABC objects in a vector and it will work just fine - at least at the extra cost of managing cleanup. In this case, you are not changing the contents of the vector, since the vector contains only pointers.

0


source







All Articles