teivaz teivaz - 2 months ago 9
C++ Question

How to explicitly call const version of the member function?

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?

Answer

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();
Comments