Search code examples
c++referencepolymorphismconstantsreturn-type

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


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.


Solution

  • 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.