Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a call to a const qualified function overload?

Tags:

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?  } }; 
like image 768
dawid Avatar asked Dec 05 '14 11:12

dawid


People also ask

Can const function be overloaded?

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.

Can a non-const object call a const function?

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.

Why we use const in operator overloading in C++?

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.

Why it is good practice to declare as many methods as const as you can?

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.


1 Answers

Option #1:

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();     //   ~~~~~~~^ } 

Option #2:

Make the calling function a const-qualified one:

void call() const //          ~~~~^ {     fun(); } 

DEMO

like image 71
Piotr Skotnicki Avatar answered Oct 04 '22 04:10

Piotr Skotnicki