Q:

Differences with const keyword in C++

In C++, I have some troubles understanding the difference between these 3 ways where const is used :
int get() const {return x;}        
const int& get() {return x;}      
const int& get() const {return x;} 

I'd like to have a clear explanation with examples to help me understand the differences. 

A:

Here's the most const example:
class Foo
{
    const int * const get() const {return 0;}
    \_______/   \___/       \___/
        |         |           ^-this means that the function can be called on a const object
        |         ^-this means that the pointer that is returned is const itself
        ^-this means that the pointer returned points to a const int    
};

In your particular case
//returns some integer by copy; can be called on a const object:
int get() const {return x;}        
//returns a const reference to some integer, can be called on non-cost objects:
const int& get() {return x;}      
//returns a const reference to some integer, can be called on a const object:
const int& get() const {return x;} 

This question explains a little more about const member functions.
Const references can also used to prolong the lifetime of temporaries.

