On May 19, 7:52 pm, Victor Bazarov <v.baza...@comcast.invalid> wrote:
> On 5/19/2010 2:41 PM, none wrote:
> > I have extended a library class 'LibraryBase' which I cannot
> > modify. 'LibraryBase' contains a const function
> > 'ConstFunction'. In my subclass 'LibrarySub' I am overriding
> > 'ConstFunction'. But in this function I now need to call
> > a non const function.
> > But that gives an error and as I understand also violates
> > the const principle.
> > But is there no way to call a non const function from a const function?
> > Here is a basic example:
> > class Test {
> > public:
> > void testConst() const {
> > // this is a no go!
> > testNonConst();
> > }
> > void testNonConst() {
> > }
> > private:
> > };
> > int main(){
> > Test t;
> > t.testConst();
> > return 0;
> > }
> The only legal way is to do a const_cast on 'this'. And only
> do it if you know that your object is non-const, which you
> probably can't know since the system is going to be calling
> your 'ConstFunction'...
There's no problem calling a non-const function on a const
object, as long as the function doesn't actually modify the
object in any way.
> Why do you need to call the non-const function?
Probably because the class in question isn't const-correct. He
says he can't modify it, which means that he probably got it
from somewhere else, where they didn't worry about const.
> The whole point in having the 'const' in a function is to
> promise that the state of the object is not going to change
> during the call. You're violating that promise. Could it be
> you're overriding a wrong function?
He's only violating the promess if the base class function
actually does modify something. The original poster, you and
I know enough to make this promess explicit with the const
keyword, but there are doubtlessly still a lot of people around
who don't know that---including, perhaps, the author of the
original class.
--
James Kanze
|