Operator + = overload, why const?

Possible duplicate:
What is the meaning of a constant at the end of a member function?

Dear,

I tried to overload the + = operator, and I got some error "discard qualifiers", only adding "const" at the end of the method, I was able to get rid of the error. Can someone explain to me why this is necessary? Below is the code.

class Vector{
    public:
        Vector();
        Vector(int);

        //int getLength();
        int getLength() const;
        const Vector & operator += (const Vector &);

        ~Vector();
    private:
        int m_nLength;
        int * m_pData;
};

/*int Vector::getLength(){
    return (this->m_nLength);
}*/

int Vector::getLength() const{
    return (this->m_nLength);
}

const Vector & Vector::operator += (const Vector & refVector){
    int newLength = this->getLength() + refVector.getLenth();
    ...
    ...
    return (*this);
}
+3
source share
8 answers

The method operator+=receives its argument as a reference to a constant, therefore it is not allowed to change the state of the received object.

Therefore, through the const-reference (or const-pointer) you can:

  • ( ),
  • const ( , ),
  • , mutable ( ).

, .

+2

+= , *this, . const.

Vector &Vector::operator+=(const Vector &refVector);

, const ( ), const (refVector).

+2

getLength refVector, const Vector &. const const.

+2

operator+= refVector; const const, getLength() const.

+1

refVector.getLength(), refVector const Vector & refVector, getLength ok const.

0

operator+= const Vector&, getLength().

getLength() const, ( ) const.

const getLength(), , const.

0

refVector const Vector&, - const Vector.

const , this const objects.

0

operator+= refVector const. , , .

const , . , int getLength(); refVector refVector.getLength();. int getLength() const; . , .

0

Source: https://habr.com/ru/post/1774518/


All Articles