Search code examples
c++inner-classes

Why can I not pass 'this' to an inner class's method in this case?


I have a class containing an inner class that looks somewhat like this:

class Foo
{
    class Bar
    {
    public:
        void update(const Foo& f)
        {
            //Updates using public getters of Foo
        }
    };
public:
    void doStuff() const
    {
        b_.update(*this);
    }
private:
    Bar b_;
};

The line b_.update(*this) is currently giving me the error cannot convert 'this' pointer from 'const Foo::Bar' to 'Foo::Bar &'

Why is that? The update method's parameter is of type const Foo&, meaning it couldn't possibly modify the Foo object if it wanted to. Shouldn't that satisfy the const method doStuff?

I've tried googling for someone having the same problem for an hour but I can't seem to word it correctly in order to find a similar question.

Is what I'm trying to do possible, or do I need to change my design?


Solution

  • doStuff is const therefore b_ is also const in this context so calling the non-const update function is not allowed.

    If doStuff needs to modify b_ it should not be marked const, you could mark b_ as mutable but that's rarely the correct thing to do.