Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a non-const member function from a const member function

Tags:

c++

constants

I would like to know if its possible to call a non-const member function from a const member function. In the example below First gives a compiler error. I understand why it gives an error, I would like to know if there is a way to work around it.

class Foo
{
   const int& First() const
   {
         return Second();
   }

   int& Second()
   {
        return m_bar;
   }

   int m_bar;
}

I don't really want to discuss the wisdom of doing this, I'm curious if its even possible.

like image 518
Steve Avatar asked Oct 28 '10 21:10

Steve


People also ask

Can we call non-const member function from const member 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.

What will happen if a const object calls a non-const member function?

If the function is non-constant, then the function is allowed to change values of the object on which it is being called. So the compiler doesn't allow to create this chance and prevent you to call a non-constant function on a constant object, as constant object means you cannot change anything of it anymore.

Can we invoke non-const member function using a pointer reference to const?

Yes, in the sense that it can be const_cast away, or the object can have mutable members.

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.


2 Answers

return (const_cast<Foo*>(this))->Second();

Then cry, quietly.

like image 58
Adam Wright Avatar answered Sep 18 '22 10:09

Adam Wright


It is possible:

const int& First() const 
{ 
    return const_cast<Foo*>(this)->Second(); 
}

int& Second() { return m_bar; }

I wouldn't recommend this; it's ugly and dangerous (any use of const_cast is dangerous).

It's better to move as much common functionality as you can into helper functions, then have your const and non-const member functions each do as little work as they need to.

In the case of a simple accessor like this, it's just as easy to return m_bar; from both of the functions as it is to call one function from the other.

like image 31
James McNellis Avatar answered Sep 21 '22 10:09

James McNellis