I have an overloaded member function in single class. The differences between two return type and const modifier:
class A
{
public:
    int mass() const {return m_mass;}
protected:
    int& mass() {return m_mass;}
private:
    int m_mass;
};
But by default having non-const instance of class A will cause non-const version of overloaded function to be called:
int main() 
{
    A a;
    return (const int)a.mass();
}
error:
int& A::mass()is protected within this context
How can the const version be called explicitly in this case?
C++17 will introduce std::as_const, which is a really simple utility that you can implement yourself until then:
A a;
std::as_const(a).mass();
                        You simply use a named const reference to it, or better still, use const_cast to obtain an unnamed const reference to it, then call.
int main() 
{
    A a;
    //1
    const A& a_const = a;
    a_const.mass();                
    //2
    const_cast<const A&>(a).mass(); 
    //3
    //in C++17
    //std::as_const(a).mass();          //3
}
With C++17 and later you can use std::as_const.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With