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);
}
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:
const qualifier (which indicates that this method is guaranteed not to modify the internal state of the object),mutable (which is very seldomly used and not relevant here).Hope that helps.
+= 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With