Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator += overload, why const? [duplicate]

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);
}
like image 406
Javier Avatar asked Jan 24 '26 06:01

Javier


2 Answers

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.

like image 155
Kos Avatar answered Jan 26 '26 21:01

Kos


+= modifies its left-hand argument, which is *this when you overload it for a class. Therefore, you can't make that argument const. Instead, use

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

That being said, because its right-hand argument has to be const (by definition), you can't call a non-const member function on the right-hand argument (refVector).

like image 45
Fred Foo Avatar answered Jan 26 '26 20:01

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!