0
votes

passing ‘const IntBag’ as ‘this’ argument discards qualifiers [-fpermissive]

This is my code: '''C++ **

> int IntBag::operator[](int index){     //get array item
>         return array_[index];
>     }
>     
>     IntBag::IntBag (const IntBag& a){        //copy constructr
>       size=a.getSize();
>       for(int i=0; i<size; i++){
>         int val=a[i];
>         array_[i]=val;
>       }
>     }
>     
>     int IntBag::getSize()const{    //get the size of the array
>       return size;
>     }
>     
>     IntBag& IntBag::operator = (const IntBag& a){
>       for(int i= 0; i< a.getSize(); i++) {
>         array_[i]=a[i];
>       }
>     }

**


My error is: $ g++ intbag.cpp intbag.cpp: In copy constructor ‘IntBag::IntBag(const IntBag&)’: intbag.cpp:19:16: error: passing ‘const IntBag’ as ‘this’ argument discards qualifiers [-fpermissive] 19 | int val=a[i]; | ^ intbag.cpp:12:5: note: in call to ‘int IntBag::operator’ 12 | int IntBag::operator[](int index){ //get array item | ^~~~~~ intbag.cpp: In member function ‘IntBag& IntBag::operator=(const IntBag&)’: intbag.cpp:30:18: error: passing ‘const IntBag’ as ‘this’ argument discards qualifiers [-fpermissive] 30 | array_[i]=a[i]; | ^ intbag.cpp:12:5: note: in call to ‘int IntBag::operator’ 12 | int IntBag::operator[](int index){ //get array item | ^~~~~~ intbag.cpp:32:1: warning: no return statement in function returning non-void [-Wreturn-type] 31 | } +++ |+ return *this; 32 | } | ^


enter image description here

1
Don't post images of text. Copy the text instead.eerorika
Do not use the C tag for C++ questions.Eric Postpischil

1 Answers

1
votes

How to remove this fpermissive error in c++?

Don't call non-const qualified member functions on const values. In this case the non-const qualified member function is the subscript operator overload and the const value is the argument const IntBag& a of the assignment operator overload.

Given that the subscript operator overload doesn't modify the state of the object, nor return a non-const reference, there is no need for it not to be const qualified. As such, a simple solution is to declare the subscript operator const.