Difference between function returning by reference and const function returning a const value

79 views Asked by At

I was making a class for arrays to work as stacks and encountered upon two types of functions to return the top element. I cannot understand the difference between the two and how the compiler decides which one of the two to call. Beloww is the code for the two.

T & getTop() {                //function 1
    return arr[top - 1];
}
const T & getTop() const {   //function 2
    return arr[top - 1];

the 'top' variable points to the current empty cell in the array and T is the generic datatype.

Thank you for your help in advance.

3

There are 3 answers

1
Incomputable On BEST ANSWER

I suppose your stack is called stack.

stack<T> s;
/*do something with it*/
s.getTop(); //will call the non const version
std::as_const(s).getTop() //will call const version

And similarly:

const stack<T> s;
s.getTop() //const version

So, if the type of the variable is not const, it will call non const version. Otherwise it will invoke const version.

0
dsapandora On

You can see this answer for reference but in a few words for this specific case looks like is for tell to others methods won't change the logical state of the object.

0
Jack On

A const T& reference doesn't allow to modify the referenced data. Notice that the second getTop() method is declared as const too to specify that the method doesn't modify the state of the instance on which this is called.

Two implementations are required to allow getting the top element from a context in which the instance that contains the array is const and at the same time allowing to modify the top element in contexts in which it's not const.

This is part of a bigger concept named const correctness, you can get additional info about it here, specifically: