Can someone explain what is the point of returning by constant reference? I know that when you just return a reference, you are returning an alias to that object you are returning. However, I am not sure what adding the word 'const' changes what it does. Thanks!
            Asked
            
        
        
            Active
            
        
            Viewed 84 times
        
    -1
            
            
        - 
                    `const` means it can't be changed. – ChrisMM Jul 20 '20 at 18:00
 - 
                    `const` forces the program to let the reference constant. It also may be a hint for compiler to do some optimizations – Jan Stránský Jul 20 '20 at 18:01
 - 
                    to have a read only ref. for example – asmmo Jul 20 '20 at 18:01
 - 
                    @Goddrew Ask yourself what the qualifier const means. – Vlad from Moscow Jul 20 '20 at 18:01
 - 
                    1Does this answer your question? [C++ Return value, reference, const reference](https://stackoverflow.com/questions/21778045/c-return-value-reference-const-reference) – Rohan Bari Jul 20 '20 at 18:07
 
2 Answers
2
            
            
        A good example would be std::vector::operator[].  There are two overloads of that function, a const version that returns a const reference and a non-const version that returns a regular reference.  If you use the const version you cannot assign a new value.
void func(const std::vector<int> & const_vec, std::vector<int> & vec)
{
    const_vec[0] = 906;  // will fail with compiler error
    vec[0] = 906;  // works fine if vec.size() >= 1
}
        Mark Ransom
        
- 299,747
 - 42
 - 398
 - 622
 
1
            
            
        Most times the point in returning a "const ref" (a reference to a constant object) is to give the calling code read only access to the property of a class.
T const & (or const T &) denotes a reference to an object that can't be altered using the reference. Hence only const-qualified member functions can be called.
        Swordfish
        
- 12,971
 - 3
 - 21
 - 43
 
- 
                    
 - 
                    2But don't use a cast unless you know ***exactly*** what you are doing. And probably not even then. – user4581301 Jul 20 '20 at 18:17
 -