Search code examples
c++constantsfunction-qualifier

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


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.


Solution

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

    Then cry, quietly.