-7

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.

Kruncho
  • 195
  • 1
  • 13

2 Answers2

2

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.

Community
  • 1
  • 1
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • Nice answer, but I would expand a little the part on the const member function. It can be called on a const object, yes, but I would add that it is a promise not to change any of the member variables, nor to call any non-const member function, and that this promise is enforced by the compiler, which will give an error if you violate it. – Fabio says Reinstate Monica Oct 15 '15 at 08:51
  • Thank you @SingerOfTheFall, I know it's a basic question but that wasn't very clear in my mind – Kruncho Oct 15 '15 at 08:53
0
 (1) int get() const {return x;}   

We have two advantages here,

  1. const and non-const class object can call this function. 

  const A obj1;
  A obj1;

  obj1.get();
  obj2.get();

    2. this function will not modify the member variables for the class

    class A
    {
       public: 
         int a;
       A()
       {
           a=0;
       }
       int get() const
       {
            a=20;         // error: increment of data-member 'A::a' in read-only structure
            return x;
       }
     }

While changing the member variable of the class [a] by constant function, compiler throws error.

    (2) const int& get() {return x;}  

returning the pointer to constant integer reference.

    (3)const int& get() const {return x;} 

it is combination answer (2) and (3).

Eswaran Pandi
  • 602
  • 6
  • 10