Search code examples
c++classconstantsoperator-overloadingfunction-qualifier

operator += overload, why const?


Possible Duplicate:
What is the meaning of a const at end of a member function?

Dear all,

I was trying to overload the operator += and I was getting some error of "discard qualifiers", only by adding "const" at the end of a method, I was able to get rid of the error. Does anybody could explain me why this is needed? Below, 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);
}

Solution

  • The operator+= method receives its argument as a reference-to-constant, so it is not allowed to modify the state of the object it receives.

    Therefore, through a reference-to-const (or pointer-to-const) you may only:

    • read the accessible fields in that object (not write),
    • call only the methods with the const qualifier (which indicates that this method is guaranteed not to modify the internal state of the object),
    • read or write accessible fields declared as mutable (which is very seldomly used and not relevant here).

    Hope that helps.