I find it irritating that I can call non-const functions of an object if I have a pointer to this object. I cannot let the pointer be a const pointer because there are also non-const functions I need to call. Therefore, my only option seems to do static_casts to ensure that constness also works across pointers. Here is a minimal example:
class MyClassImpl
{
MyClassImpl(void) : m_i(0) {}
int increment(void) {
++m_i;
return m_i;
}
private:
int m_i;
};
class MyClass
{
MyClass(void) : m_pImpl(new MyClassImpl()){}
~MyClass(void) {
delete m_pImpl;
}
int doNothing(void) const {
m_pImpl->increment(); // works although MyClassImpl::increment() is non-const
// static_cast<const MyClassImpl *>(m_pImpl)->increment(); // this will not compile because of non-constness
}
private:
MyClass(const MyClass & rhs);
MyClassImpl * m_pImpl;
};
However, I wonder if the static_cast has any cost at runtime. Are static_casts completely evaluated at compile time or is there some overhead, assuming that doNothing() is called often.
Edit: My question is different from C++ static_cast runtime overhead because in my case, the static_cast only adds const. Other users finding this question might be interested in the mentioned question.