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.
I suppose your stack is called
stack
.And similarly:
So, if the type of the variable is not const, it will call non const version. Otherwise it will invoke const version.