Question about const qualifier in functions.

Hey I have a quick question about when I'm suppose to use this const qualifier in my functions.

Let's say I am trying to add two objects from a user defined class Vector.

My function definition is as follows :

1
2
3
4
Vector Vector::operator+(const vector & b) const
{
return Vector(x + b.x, y+b.y);
}


I assume this is appropraite use(i've seen it used this way) but I'm not 100% sure on why.. with the previous definition, as i understand it, the const is there because I'm not editing values v1 & v2 and the function should not edit their values?( see following code ) or (if yes but not only for that reason) what other purposes does it serve?

1
2
3
 Vector v1, v2, v3;
//declare some values for v1 & v2 other than what was assigned in the default constructor
v3 = v1+ v2;


I appreciate any time you sacrifice in reviewing my question. I'm just curious because I feel I need to understand this chapter 100% before I move into the next chapter which builds off of this chapter.


In a nutshell : I assume my understanding of the use of the const qualifier to be correct, in that the function should not edit the implicit nor the explicit parameter, but are there other uses for this const qualifier?
Last edited on
A member function that logically would not modify 'this' should be const.

In your operator + example, making it const is good because the operator will not modify the left side of the + operator:

1
2
3
Vector v1, v2, v3;

v3 = v1 + v2;  // neither v1 nor v2 are modified by this, therefore both should be const 


1
2
3
4
5
Vector Vector::operator+(const vector & b) const
                          ^                  ^
                          |              Makes v1 const (v1 is 'this')
                          |
                      makes v2 const


The reason making them const is benefitial is because you cannot call a non-const function with a const object:

1
2
3
4
const Vector v1(0,0);
Vector v2, v3;

v3 = v1 + v2;  // fails unless the + operator is const, because 'v1' is const, it must be passed as const 
Topic archived. No new replies allowed.