Based on C++ standard (standard version >= C++11), there are two top()
methods available for std::stack
template class.
reference top();
const_reference top() const;
What’s the difference between the two methods? and how do I know which one I’m calling? For example,
std::stack<int> si;
si.push(4);
si.top(); // which method is this?
I wrote something similar:
struct S {
int x {5};
int &foo();
const int &foo() const;
};
const int &S::foo() const { fmt::println("const int &"); return x;}
int &S::foo() { fmt::println("int &"); return x;}
Every time I call .foo()
, int &foo()
is picked.
New contributor
RS SR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.