I would like to know if its possible to call a non-const member function from a const member function. In the example below First gives a compiler error. I understand why it gives an error, I would like to know if there is a way to work around it.
class Foo
{
const int& First() const
{
return Second();
}
int& Second()
{
return m_bar;
}
int m_bar;
}
I don't really want to discuss the wisdom of doing this, I'm curious if its even possible.
const function use cases A const function can be called by either a const or non- const object. Only a non- const object can call a non- const function; a const object cannot call it.
If the function is non-constant, then the function is allowed to change values of the object on which it is being called. So the compiler doesn't allow to create this chance and prevent you to call a non-constant function on a constant object, as constant object means you cannot change anything of it anymore.
Yes, in the sense that it can be const_cast away, or the object can have mutable members.
Converting between const and non-const For instance, you can pass non-const variables to a function that takes a const argument. The const-ness of the argument just means the function promises not to change it, whether or not you require that promise.
return (const_cast<Foo*>(this))->Second();
Then cry, quietly.
It is possible:
const int& First() const
{
return const_cast<Foo*>(this)->Second();
}
int& Second() { return m_bar; }
I wouldn't recommend this; it's ugly and dangerous (any use of const_cast
is dangerous).
It's better to move as much common functionality as you can into helper functions, then have your const and non-const member functions each do as little work as they need to.
In the case of a simple accessor like this, it's just as easy to return m_bar;
from both of the functions as it is to call one function from the other.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With