I'm trying to call const
function inside a class, but a non-const
function with the same name exists.
Note: I can't just change names.
class MyQuestion { void fun() { cout<<"a"; } void fun()const { cout<<"b"; } void call() { fun();//<how to call fun() const? } };
Overloading on the basis of const type can be useful when a function returns a reference or pointer. We can make one function const, that returns a const reference or const pointer, and another non-const function, that returns a non-const reference or pointer. See this for more details.
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.
The const qualifier ensures that the parameter (param) is not altered inside the operator=() method. The above method alters the right hand side operand 'param' after assigning the value to the left hand side operand. The const qualifier helps you not to violate the semantics of the assignment operation.
A function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.
Call that function through a pointer to a const
qualified type:
void call() { static_cast<const MyQuestion*>(this)->fun(); // ~~~~^ }
c++11:
void call() { const auto* that = this; //~~^ that->fun(); }
c++17:
void call() { std::as_const(*this).fun(); // ~~~~~~~^ }
Make the calling function a const
-qualified one:
void call() const // ~~~~^ { fun(); }
DEMO
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