kamikaze_pilot kamikaze_pilot - 1 month ago 23
C++ Question

casting non const to const in c++

I know that you can use

const_cast
to cast a
const
to a non-
const
.

But what should you use if you want to cast non-
const
to
const
?

Answer

const_cast can be used in order remove or add constness to an object. This can be useful when you want to call a specific overload.

Contrived example:

class foo {
    int i;
public:
    foo(int i) : i(i) { }

    int bar() const {
        return i;    
    }

    int bar() { // not const
        i++;
        return const_cast<const foo*>(this)->bar(); 
    }
};