Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 legacy code so that it now looks like this:

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

The problem is that I'm getting this error:

In member function 'virtual int Random() const': class.cc:145: error: passing 'const int' as 'this' argument of 'int newCall(int)' discards qualifiers 

Now I know in order to fix this error I can make my newCall() a const function. But then I have several funciton calls in newCall() that I have to make, so now I would have to make all of those function calls const. And so on and so forth until eventually I feel like half my program is going to be const.

My question: is there any way to call a function within Random() that isn't const? Or does anyone have any ideas on how to implement newCall() within Random() without making half my program const.

Thanks

-josh

like image 446
Grammin Avatar asked Feb 15 '11 19:02

Grammin


People also ask

Can a const function call a non-const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.

How do you call a non-const method from the const method?

Casting away const relies on the caller only using the function on non-const objects. A potential solution is to alter the code in // .... so that it doesn't need to use the object's "current color". Add versions of all the functions you use, that take a QColor parameter instead.

Can you pass a non-const to a const?

Converting between const and non-const For instance, you can pass non-const variables to a function that takes a const argument. The const-ness of the argument just means the function promises not to change it, whether or not you require that promise.

Can a const function return a non-const reference?

If the thing you are returning by reference is logically part of your this object, independent of whether it is physically embedded within your this object, then a const method needs to return by const reference or by value, but not by non-const reference.


1 Answers

int Random() const {   return var_ ? const_cast<ClassType*>(this)->newCall(4) : 0; } 

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

like image 122
Nawaz Avatar answered Sep 18 '22 04:09

Nawaz