How to call a non-const function within a const function (C++)

后端 未结 7 664
天命终不由人
天命终不由人 2020-12-10 01:06

I have a legacy function that looks like this:

int Random() const
{
  return var_ ? 4 : 0;
}

and I need to call a function within that lega

相关标签:
7条回答
  • 2020-12-10 01:43
    int Random() const
    {
      return var_ ? const_cast<ClassType*>(this)->newCall(4) : 0;
    }
    

    But it's not a good idea. Avoid if it's possible!

    0 讨论(0)
  • 2020-12-10 01:48

    There are two possibilities here. First, newCall and ALL of its callees are in fact non-modifying functions. In that case you should absolutely go through and mark them all const. Both you and future code maintainers will thank you for making it much easier to read the code (speaking from personal experience here). Second, newCall DOES in fact mutate the state of your object (possibly via one of the functions it calls). In this case, you need to break API and make Random non-const to properly indicate to callers that it modifies the object state (if the modifications only affect physical constness and not logical constness you could use mutable attributes and propagate const).

    0 讨论(0)
  • 2020-12-10 01:49

    if it's really a random number generator, then the number generation code/state could likely be placed in a class-local static generator. this way, your object is not mutated and the method may remain const.

    0 讨论(0)
  • 2020-12-10 01:50

    The const qualifier asserts that the instance this of the class will be unchanged after the operation, something which the compiler cant automagically deduce.

    const_cast could be used but its evil

    0 讨论(0)
  • 2020-12-10 01:53

    you should alter your program to use/declare const correctly...

    one alternative is to use const_cast.

    0 讨论(0)
  • 2020-12-10 01:56
    const_cast<MyClass *>(this)->newCall(4)
    

    Only do this if you're certain newCall will not modify "this".

    0 讨论(0)
提交回复
热议问题