Confused about const and & in member funnctions

I am learning about creating a class and its member functions but am having a hard time understanding the meaning of const and &. I'll list the funcs first.

Func1:
1
2
3
4
5
6
7
8
9
10
11
12
class Vector
{
 	double* array;
    	int length = 0;

double operator*(const Vector& b) const
    {
        
        for (auto i=0; i<length; i++)
            d += array[i]*b.array[i];
        return d;
    }


I understand that the const before the Vector &b means the function shouldn't modify b. But what does the second const on the right mean?
------------------------------------------------------------------------------
Func2:
1
2
3
4
5
6
7
8
9
Vector& operator+(const Vector& b)
    {
        // Add two vectors
        for (auto i=0; i<length; i++)
            array[i] += b.array[i];
        
        return *this;
    }
  


Is the & before the operator telling the function to overwrite the Vector that invokes the operator?
------------------------------------------------------------------------------
Func3:
1
2
3
4
5
6
7
8
9
  
const double operator()(int index) const
    {
        if (length<index) throw "Index exceeds vector length";
        
        return array[index];
    }    

};


Neither of the const make sense to me. And why isn't the operator being invoked by reference i.e. with an &?
Thanks for your time!
Last edited on
But what does the second const on the right mean?


The function doesn't alter any of the class members.


Is the & before the operator telling the function to overwrite the Vector that invokes the operator?


The function returns a reference to Vector. Seen as you return *this , it would overwrite the original.

Neither of the const make sense to me. And why isn't the operator being invoked by reference i.e. with an &?


The first const returns a const double. See q1 for the second const. This operator is part of the class, it doesn't need a reference.
Topic archived. No new replies allowed.