Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

How do I call a non-const member function from a const object?

My question is pretty simple and straight-forward. I have a class S with two member functions, f and h. In f I make a const S object. However, I can't call its h method as the object is const and h is not (and the compiler can't guarantee that I won't modify the S object). I don't want to make another h function (as I'll duplicate the function) and I don't want to make the h I have const. So how would I call it? Here is the code I have:

    struct S {

        void h() {}

        void f() {

            const S & s = *this;

            s.h();

        }

    };

    int main() {

        S s;

        s.f(); // error line 8

    }

Any and all answers are appreciated.

2 Answers

Relevance
  • oops
    Lv 6
    8 years ago
    Favorite Answer

    At some point, you ran into a problem, and thought of a solution. However, that solution simply caused another problem(the one you are asking about). Now you've simplified the code into a minimal example and are asking how to solve your secondary problem, instead of the primary problem. I assert that your solution to the primary problem is inherently flawed. Breaking const correctness is pretty much always the wrong thing to do. Unfortunately, your simplification of the code has erased all signs of the primary problem, and so I can't help you with an actual solution.

    If you really want to call a non-const function on a const object, you do it like this:

        (const_cast<S&>(s)).h();

    But if you do this on an object that is in fact const, it is undefined behavior.

    Here's a guess for you:

    Does h() modify a data member, but you don't want that member to be factored into whether the object is const or not? Are you aware of the 'mutable' keyword? Would it help in your situation?

    http://en.cppreference.com/w/cpp/language/cv

  • 8 years ago

    You could do:

    this->h(); // Since this and s reference the same object, h will get the same this pointer.

    Or you can cast away the constness: (which is usually a bad idea)

    ((S &)s).h();

Still have questions? Get your answers by asking now.