Calling a const function rather than its non-const version

前端 未结 4 1440
深忆病人
深忆病人 2020-11-28 13:38

I tried to wrap something similar to Qt\'s shared data pointers for my purposes, and upon testing I found out that when the const function should be called, its non-const ve

4条回答
  •  情歌与酒
    2020-11-28 13:49

    But testType is not a const object.

    Thus it will call the non const version of its members.
    If the methods have exactly the same parameters it has to make a choice on which version to call (so it uses the this parameter (the hidden one)). In this case this is not const so you get the non-const method.

    testType const test2;
    test2->x();  // This will call the const version
    

    This does not affect the call to x() as you can call a const method on a non const object.

提交回复
热议问题