An example where we need const_cast in C++

class Example
{
public:

    Example()
    {
        m.emplace("abc", 13);
    }

    const int& findValue(const std::string& val) const
    {
        auto i = m.find(val);

        if (i == m.end()) {
            throw std::runtime_error(std::format("Key {} not found.", val));
        }

        return i->second;
    }

    int& findValue(const std::string& val)
    {
        return const_cast<int&>(
            const_cast<const Example*>(this)->findValue(val));
    }
private:

    std::map<std::string, int> m;
};

int main()
{
    Example a;

    a.findValue("abc") = 25;

    std::cout << a.findValue("abc") << std::endl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *