Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 304
Teivaz Avatar asked Sep 19 '25 16:09

Teivaz


2 Answers

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();
like image 138
Barry Avatar answered Sep 21 '25 07:09

Barry


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.

like image 26
WhiZTiM Avatar answered Sep 21 '25 05:09

WhiZTiM